1.获取java工程中src目录中的文件
示例:获取src目录下的test.properties文件
public class GetFileFromSrcPath
{
public static void main(String[] args)
{
InputStream is = GetFileFromSrcPath.class.getResourceAsStream("/test.properties");
}
}
2.获取java web工程中的webinf路径
request.getSession().getServletContext().getRealPath("/WEB-INF");
3.java web工程中的普通类获取webinf路径
public clas Test
{
public static void main(String[] args)
{
String tempPath = Test.class.getResource("/").getPath(); // 获取了工程中的classes目录(该目录位于webinf下面)
String webinfPath = tempPath.substring(0, tempPath.lastIndexOf("classes"));
// 取得webinf的路径
System.out.println(webinfPath); // 在控制台中输出webinf的路径
}
}

本文介绍了如何在Java工程和Java Web工程中获取src目录下的文件以及WEB-INF路径。对于Java工程,可以使用`getResourceAsStream()`方法获取src目录下如`test.properties`的文件。在Java Web工程中,可以通过`getSession().getServletContext().getRealPath("/WEB-INF")`获取WEB-INF路径,或在普通类中利用`getResource()`结合字符串操作获取WEB-INF路径。

被折叠的 条评论
为什么被折叠?



