讀取資源文件失敗!!!
在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包內的文件的,所以會報錯。