在Linux上读取jar包BOOT-INF/classes下的properties文件
把spring boot项目打包成jar包后部署到Linux上测试时,出现读取BOOT-INF/classes下的properties文件,一直提示该路径下的文件不存在,但是进去查看是,该文件是存在,但就是读取不到。
该文件路径如下
使用的代码是
**
* 获取项目根目录(动态)
* @return
*/
public static String getProjectRootPath() {
String path=null;
try{
path =CommonUtil.class.getResource("/").getPath();
}catch(Exception e){
File directory = new File(NULL_STRING);
path= directory.getAbsolutePath()+File.separator;
}
return path;
}
原因是在本地window上读取时磁盘上是有该文件的真实路径存在,使用该代码确实没问题。但是在Linux上,打包成jar后,Resource下的文件是存在于jar这个文件里面,在磁盘上是没有真实路径存在的,它是位于jar内部的一个路径。
所以读取的方式需要改变。
把读取的代码改为以下代码(可以读取txt,json,properties等文件)
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("loadFFmpeg.properties");
也可以使用以下方式(我自己使用的是第一种)
InputStream inputStream = new ClassPathResource("loadFFmpeg.properties").getInputStream();
另一种
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("loadFFmpeg.properties");