JavaEE无法获取项目根节点的文件 编译时不会被放到tomcat webapps中
使用类加载器获取src下的文件路径两种方式
/*
* 获取classPath下的文件 即src下的文件
*/
FileInputStream inputStream = new FileInputStream("src/one.txt");
/*
* getResource参数必须加 '/' 斜杠代表src(即classPath路径)
*/
String path = Test.class.getResource("/two.txt").getPath();
FileInputStream inputStream = new FileInputStream(path);
System.out.println(path);
/*
* getResource 参数路径相对于 tomcat webapps\Test\WEB-INF\classes目录
* 获得classes(src目录)下的任何资源 getResource参数不可加 '/' 默认已经有斜杠
*/
URL url = Test.class.getClassLoader().getResource("Test.properties");
FileInputStream inputStream = new FileInputStream(url.toString().substring(6));
System.out.println(url);
JavaEE获取WebContent下的文件路径
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*
* 获取webContent下的资源文件路径 前提必须在tomcat环境下tomcat启动后
* getRealPath的参数 没有限制 加不加'/'都可以 ? 下面两个参数结果完全相同
* /webapps/Test/WebContent/WEB-INF/web.xml == /WEB-INF/web.xml
*/
String value = request.getSession().getServletContext().getRealPath
("/WEB-INF/web.xml");
FileInputStream inputStream = new FileInputStream(value);
System.out.println(value);
}
console打印
/D:/eclipse/ECLIProjects/Test/build/classes/Test.properties
file:/D:/eclipse/ECLIProjects/Test/build/classes/Test.properties
D:\Common documents\apache-tomcat-7.0.92\webapps\Test\WEB-INF\web.xml