读取资源文件失败!!!
在Windows平台开发过程中能正常运行,但是将SpringBoot项目打jar包运行就会报错,我们一起来看看究竟是什么导致的?
案发现场:
java.io.FileNotFoundException: class path resource [com/aden/modules/demo/mock/json/task_process.json] cannot be resolved to absolute file path because it does
not reside in the file system: jar:file:/E:/code/aden/adenx/adenx-fast/adenx-fast-web/target/adenx-fast-web-1.0.0-exec.jar!/BOOT-INF/lib/adenx-fast-manager-api-1.0.0.jar!/com/aden/modules/demo/mock/json/task_process.json
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:217)
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:180)
at com.aden.modules.demo.mock.MockController.readJson(MockController.java:191)
at com.aden.modules.demo.mock.MockController.taskProcess(MockController.java:173)
at com.aden.modules.demo.mock.MockController$$FastClassBySpringCGLIB$$31542cbb.invoke(<generated>)
readJson方法源码:
private String readJson(String jsonSrc) {
StringBuilderjson = new StringBuilder("");
try {
File file = ResourceUtils.getFile(jsonSrc);
Path path = Paths.get(file.getPath());
Files.lines(path)
// 使用Stream很容易的过滤掉包含的空格
.map(String::trim)
.forEach(json::append);
System.out.println(json.toString());
System.out.println(json.toString().length());
} catch (IOException e) {
e.printStackTrace();
}
return json.toString();
}
解决方案:
采用读取流的方式访问文件:
ClassPathResource resource = new ClassPathResource("task_process.json");
InputStream inputStream = resource.getInputStream();
原因分析:
项目打成jar包后,资源文件也存在于jar包中,
文件的绝对路径是jar:file:/E:/code/aden/adenx/adenx-fast/adenx-fast-web/target/adenx-fast-web-1.0.0-exec.jar!/BOOT-INF/lib/adenx-fast-manager-api-1.0.0.jar!/com/aden/modules/demo/mock/json/task_process.json
但在运行过程中,spring是不允许直接访问jar包内的文件的,所以会报错。