场景:
在Springboot中利用Resource来获取文件并在前端返回该文件, 本地测试正常, 打包到远程报错:流java.io.FileNotFoundException: class path resource [templates/startProcess.flt] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/home/work/project/console.jar!/BOOT-INF/classes!/templates/xxx.flt
排查 jar包里文件地址是没问题的
原因:
org.springframework.core.io.Resource 这个类的getFile()方法, 会自动获取构建resource对象带参构造中的url, 然后根据这个url确定该文件的类型. 因为在本地时调试时, 通过resource.getFile()获取的url类型的 protocol 属性为File, 所以可以自动生成文件; 然而在将项目打包成jar部署在服务器上时, 因为该文件是在jar里面的. 因此通过resource.getFile()获取的url类型的 protocol 属性为jar. 所以抛出该异常 cannot be resolved to absolute file path because it does not reside in the file system: url.
解决方案:
通过流来获取jar里面的文件,然后通过输出流将其输出.
修改前代码:
Resource resource = new ClassPathResource("tmep/xxx.txt");
File sourceFile = resource.getFile();
return FileUtils.readFileToString(sourceFile, "UTF-8");
修改后代码
Resource resource = new ClassPathResource("tmep/xxx.txt");
return getFileText(resource.getInputStream());
/**
* 获取文件内容
* @param inputStream
* @return
*/
public static String getFileText(InputStream inputStream) {
StringBuilder textBuilder = new StringBuilder();
try {
Reader reader = new BufferedReader(new InputStreamReader(inputStream,
Charset.forName(StandardCharsets.UTF_8.name())));
int line = 0;
while ((line = reader.read()) != -1) {
textBuilder.append((char) line);
}
} catch (IOException e) {
log.error("getFileText error", e);
throw new RuntimeException(e);
}
return textBuilder.toString();
}