读取resources 资源并转换成file
项目场景:从resources 目录下读取json 文件获取file
问题描述: 在本地项目中没有任何问题,结果在spring boot 打jar 之后执行报错
java.io.FileNotFoundException: class path resource [/static/xxxxx.json] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/app.jar!/BOOT-INF/classes!/static/xxxxxxx
代码示例:
Resource resource = new ClassPathResource(PushFcmApnsProperties.androidFilePath);
FileInputStream serviceAccount = new FileInputStream(resource.getFile());
原因分析:
开发调试阶段,没有打包时,可以通过路径定位到资源文件,此时资源文件是真实存在于电脑的本地磁盘中
打包后,Spring试图访问文件系统路径,但无法访问JAR中的路径。所以报错。此时资源文件在jar包中的classes文件中
例如:
解决方案:
//更改读取方式 先通过
InputStream inputStream =Thread.currentThread().getContextClassLoader().getResourceAsStream("相对路径");
//获取文件的inputStream 流 然后转换为file创建临时文件
File bathFile = File.createTempFile("文件名", "文件格式");
FileUtils.copyInputStreamToFile(inputStream, bathFile);



