首先分两大类按web容器分类linux
一种是普通的web项目,像用Tomcat容器,特色是压缩包随着容器的启动会解压缩成一个文件夹,项目访问的时候,实际是去访问文件夹,而不是jar或者war包。web
这种的不管你是用获取路径的方法this.getClass().getResource("/")+fileNamespring
获取流的方法this.getClass().getResourceAsStream(failName);eclipse
import org.springframework.util.ResourceUtils;this
File file= ResourceUtils.getFile("classpath:test.txt");spa
或者.net
ClassPathResource classPathResource = new ClassPathResource("test.txt");调试
获取文件:classPathResource .getFile();blog
获取文件流:classPathResource .getInputStream();ip
第二种是内嵌web容器,其特色是只有一个jar文件,在容器启动后不会解压缩,项目实际访问时jar包或者war包
这种最容易遇坑,最大的坑就是,用第一种方式读取,在eclipse,本地调试,完美运行,到linux环境下,就不行.
首先用获取路径的方法this.getClass().getResource("/")+fileName,获取流的方法this.getClass().getResourceAsStream(failName);
在本地运行时,绝壁能找到,你打印出来路径,没错,是我们eclipse的工做目录,项目目录,可是在target目录下。
如今给你分析为何去到线上,就GG了,很简单,线上内嵌的工程,咱们只会放一个jar文件上去,我理解是jar里面的路径是获取不到的,jar是封闭性东西吧,不像文件夹,总不能c:/home/xx.jar/file.txt
读取jar里面的文件,咱们只能用流去读取,不能用file,文件确定要牵扯路径,jar那个路径刚刚我已经拼出来了
jar里面文件读取方式:
ClassPathResource classPathResource = new ClassPathResource("test.txt");
获取文件流:classPathResource .getInputStream();