Java各种文件路径

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

转载于:https://www.cnblogs.com/setlilei/p/10629459.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值