Java class.getClassLoader().getResource("")获取资源路径

Java web项目打包部署时发现出现平时开发过程中没有出现的错误,查看日志发现是因为代码中
获取配置文件路径有误。

一、错误分析

项目中代码:

webRootPath = MySqlDbPoolConnection.class.getClassLoader().getResource("\\").getPath();
webRootPath = new File(webRootPath).getParent();
String profilepath = webRootPath + File.separator + fullFile;       

这种方法在开发时获取到的路径是
E:\hischarts\service\hischart\target\classes\mysql_db.properties
查看目录可知路径是正确的

而将war包部署到tomcat上获取到的路径是
E:\tomcat\apache-tomcat-8.5.15-windows-x64\apache-tomcat-8.5.15\webapps\hischart\WEB-INF\mysql_db.properties
查看war包解压后的目录可知在WEB-INF\后缺少classes\。

所以项目在开发中运行无误,在部署时运行失败。

二、查看原因:

查看资料项目中获取资源文件路径
方法应该有

1、xxx.class.getClassLoader().getResource(“”).getPath();
获取src资源文件编译后的路径(即classes路径)

2、xxx.class.getClassLoader().getResource(“文件”).getPath();
获取classes路径下“文件”的路径

3、xxx.class.getResource(“”).getPath(); 缺少类加载器,获取xxx类经编译后的xxx.class路径

扫描二维码关注公众号,回复: 3889795 查看本文章

4、this.getClass().getClassLoader().getResource(“”).getPath(); 等方法。

三、测试
测试来获取这几个地址:

String str1 = DaoTest.class.getClassLoader().getResource("").getPath();
String str2 = DaoTest.class.getClassLoader().getResource("\\").getPath();
String str3 = DaoTest.class.getClassLoader().getResource("mysql_db.properties").getPath();
String str1_1 = new File(str1).getParent();
String str2_1 = new File(str2).getParent();
String str3_1 = new File(str3).getParent();

结果:
这里写图片描述

四、结果分析

分析可知项目中getResource(“\”)也许是想已取巧方式获取资源路径,但此方式容易出错。
从上面结果可以看到在开发时,这种方法确实得到正确路径,但发布时使用getResource(“\”)
得到的资源地址是:
/E:/tomcat/apache-tomcat-8.5.15-windows-x64/apache-tomcat-8.5.15/webapps/hischart/WEB-INF/classes/
getParent()后地址为:
E:\tomcat\apache-tomcat-8.5.15-windows-x64\apache-tomcat-8.5.15\webapps\hischart\WEB-INF
可知此时再getparent()就不对了。

所以为了避免这种差别,我们可以直接用
xxx.class.getClassLoader().getResource(“文件名”).getPath();
也可以用
xxx.class.getClassLoader().getResourceAsStream(“文件名”);
直接获取InputStream

猜你喜欢

转载自blog.csdn.net/u011144425/article/details/78295647