浅谈web项目读取classpath路径下面的文件

本文主要研究的是web项目下读取classpath路径下的文件的问题,具体如下:
首先分两大类,按web容器分类:
第一种是普通的web项目,像用Tomcat容器,特点是压缩包随着容器的启动会解压缩成一个文件夹,项目访问的时候,实际是去访问文件夹,而不是jar或者war包,这种的无论你是使用

//获取路径
this.getClass().getResource("/") + fileName
//Spring ResourceUtils
import org.springframework.util.ResourceUtils;
File file= ResourceUtils.getFile("classpath:resource/test.txt");

或者

Resource res = new ClassPathResource("template/test.txt");
//获取文件:
classPathResource.getFile();
//获取文件流:
classPathResource.getInputStream();

第二种是内嵌web容器,其特点是只有一个jar文件,在容器启动后不会解压缩,项目实际访问时jar包或者war包,这种最容易遇坑,最大的坑就是,用第一种方式读取,在eclipse,本地调试,完美运行,到linux环境下,就不行.
首先用获取路径的方法

this.getClass().getResource("/")+fileName

获取流的方法

this.getClass().getResourceAsStream(failName)
this.getClass().getClassLoader().getResourceAsStream(failName)

在本地运行时,绝对能找到,打印出来的路径,没错,是我们eclipse的工作目录,项目目录,但是在target目录下。
现在我们分析为什么去到线上就GG了,很简单,线上内嵌的工程,我们只会放一个jar文件上去,因为jar里面的路径是获取不到的,jar是封闭性东西,不像文件夹,总不能是 C:/home/xx.jar/file.txt。读取jar里面的文件,我们只能用流去读取,不能用file,文件肯定要牵扯路径,jar那个路径刚刚我已经拼出来了。
jar包里面文件读取方式:

import org.springframework.core.io.ClassPathResource;
ClassPathResource classPathResource = new ClassPathResource("template/test.txt")
//获取文件流
classPathResource.getInputStream();

实际读取路径如下

sun.net.www.protocol.jar.JarURLConnection:jar:file:/opt/temp/test-app/test.jar!/template/test.txt

总结
以上就是本文关于浅谈web项目读取classpath路径下面的文件的全部内容。

 

posted @ 2021-07-01 10:01  如.若  阅读(365)  评论(0编辑  收藏  举报