ClassLoader.getSystemResourceAsStream()慎用

说明

慎用 ClassLoader.getSystemResourceAsStream() 方法读取 classes 目录下的文件

适用场景

在 普通java工程中,可以使用该方法

不适用场景

在 web工程中,使用该方法是有问题的,可能无法读取classes 目录下的文件

如:在tomcat容器中,有自己的加载器,而没有使用 ClassLoader 加载器,所以导致无法读取到配置文件

推荐方式

web工程配置文件保存路径

配置文件保存在 WEB-INF\classes 目录下,该目录是 JavaEE 的标准制定的,必须叫这个名字

读取方式一

直接返回 InputStream 流

// 开头必须有 /
InputStream is = Main.class.getResourceAsStream("/log4j.properties");

或者

// 开头必须有 /
InputStream is = this.getClass().getResourceAsStream("/log4j.properties");

读取方式二

// 开头必须有 /
URL fileURL = Main.class.getResource("/log4j.properties");

或者

// 开头必须有 /
URL fileURL = this.getClass().getResource("/log4j.properties");

参考:
https://www.cnblogs.com/dennyzhangdd/p/11387200.html