项目的相对位置部署到tomcat发生改变(获得项目路径)

在java web开发中,经常会涉及到文件的读写问题,而由于部署在tomcat上之后,文件的目录结构会发生一些变化,因此常规的获取相对或绝对路径的方式用在此处会导致获取不到文件的尴尬局面,下面便介绍一下在servlet中如何读取WEB-INF下的txt文件。

这个实质是获取web-inf文件路径。。。
使用getServletContext(). 方式不好,因为只能在web服务器启动的情况下使用。Thread.currentThread().getContextClassLoader(). 也不好,,因为ClassLoader是可以被框架或者服务器动态改变的。。有些情况下路径就不对了

我总结的较好的方法
主要思路如下:
1.得到CLASS路径值。。
2.得到其父路径,即WEB-INF的路径值。
3.得到完整的WEB-INF\WEB.XML的路径值
这样在不启动web服务器的情况下,main函数也可以读取到web-inf下的配置

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static void main(String args[]) {
Properties p = new Properties();
try {
String path = Test.class.getClass().getResource("/").getPath();
path = path.substring(1, path.indexOf("classes"));
p.load(new FileInputStream(path + "parameter.properties"));
//读出具体的参数
System.out.println("mysql_url="+p.get("mysql_url"));
System.out.println("mysql_user="+p.get("mysql_user"));
System.out.println("mysql_password="+p.get("mysql_password"));

} catch (Exception e) {
e.printStackTrace();
}
}

详情参照:
https://bbs.csdn.net/topics/390533227/
https://blog.csdn.net/qq_32623363/article/details/79948936