项目中同事问的问题,本来是直接利用绝对路径读取的。利用System.getProperty(“user.dir”)‘’这个方法进行获取项目的路径,但是他要求用相对路径获取,就试了下一下的方法:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
InputStream in = ClassLoader.getSystemResourceAsStream("spring-mvc.xml");
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String line;
while((line=br.readLine())!=null){
System.out.println(line);
}
br.close();
in.close();
}
}
亲测可用!并且百度到另以文章:http://regedit-123.iteye.com/blog/1126130
使用ClassLoader.getSystemResourceAsStream("/mypropertiestest.properties")和Thread.currentThread().getContextClassLoader().getResourceAsStream("/mypropertiestest.properties")读取src下的属性文件,通过测试,在windows和Linux下的tomcat和apusic都能成功。
---------------------------------分--------------割--------------线-----------------------------------------------------------
更新:2019-03-02 12:21:12
@Marou的猪猪
该位同学在使用该方法不能完成上述功能,在这里也非常感谢他帮我指出问题。上述代码在main方法中是可以读取到,但是在部署到tomcat服务器后,就无法读取了。
最后我测试了以下方法:
Thread.currentThread().getContextClassLoader().getResource("").getPath()
// 输出路径:/tomcat/webapps/项目名/WEB-INF/classes/
得到该路径后就可以得到WEB-INF根目录了。
总结:
自己对这块知识理解不够透彻,还引人入坑,之后写博文需要更加认真!做学问要透彻,不能一知半解!
本文介绍了在Java项目中使用相对路径读取资源文件的方法,并对比了不同方式在本地与服务器环境下的表现。同时,提供了在Tomcat部署环境下获取WEB-INF目录路径的解决方案。
2654

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



