说明
文件在 .jar 包中,没有实际路径,所以无法像读取磁盘文件那样,通过路径读取
方式一:通过类加载器获取(推荐)
先获取类加载器,然后再获取 jar 中的文件
提示:下面方法支持获取 jar 中的文件;在 Tomcat 中,还支持获取 classes 目录下的文件
通过线程获取加载器(推荐)
获取jar包中名字是 FACTORIES_RESOURCE_LOCATION 的文件(只返回一个文件的URL):
URL url = Thread.currentThread().getContextClassLoader().getResource(FACTORIES_RESOURCE_LOCATION);
获取jar包中名字是 FACTORIES_RESOURCE_LOCATION 的文件(返回所有同名文件的URL):
Enumeration<URL> enume3 = Thread.currentThread().getContextClassLoader().getResources(FACTORIES_RESOURCE_LOCATION);
其他方式
Enumeration<URL> enume = TestClassLoaderCtrl.class.getClassLoader().getResources(FACTORIES_RESOURCE_LOCATION);
Enumeration<URL> enume2 = new TestClassLoaderCtrl().getClass().getClassLoader().getResources(FACTORIES_RESOURCE_LOCATION);
方式二:返回 InputStream
直接返回 InputStream 流
/表示在 .jar 包的根目录下
不加 /,表示是当前类的包路径
第一种方法(推荐)
// jar包放在 web 工程中,可以读取文件
InputStream is = this.getClass().getResourceAsStream("/log4j.properties");
第二种方法
// 注意:jar包放在 web 工程中,无法读取文件
InputStream is = Main.class.getClass().getResourceAsStream("/log4j.properties");
方式三:返回 URL
URL fileURL = Main.class.getClass().getResource("/log4j.properties");
或者
URL fileURL = this.getClass().getResource("/log4j.properties");
亲测不可用
InputStream is=this.getClass().getClassLoader().getResourceAsStream("/spring/ApplicationContext.xml");
错误原因
有的文章说此方式也可以,但亲测不可用,尤其在 web工程,因为部署在 tomcat时,tomcat 有自己的类加载器,导致this.getClass().getClassLoader() 返回为 null
例子
例子一
InputStream is=ConfigProperties.class.getResourceAsStream("/config.properties");
Properties properties = new Properties();
properties.load(is);
properties.get("version");
例子二
URL fileURL=ConfigProperties.class.getResource("/config.properties");
InputStream is = fileURL.openStream();
Properties properties = new Properties();
properties.load(is);
properties.get("version");
感谢:
https://www.cnblogs.com/Springmoon-venn/p/5483778.html