Spring Boot 讀取靜態資原始檔
阿新 • • 發佈:2018-12-31
一、需求場景
有時候我們需要在專案中使用一些靜態資原始檔,比如城市資訊檔案 ueditorConfig.json
,在專案啟動後讀取其中的資料並初始化寫進資料庫中。
二、實現
靜態資原始檔 ueditorConfig.json
放在 src/main/resources
目錄下
Resource resource = new ClassPathResource("ueditorConfig.json");
File file = resource.getFile();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file )));
ClassPathResource
類的註釋如下:
Resource implementation for class path resources. Uses either a given ClassLoader or a given Class for loading resources. Supports resolution as java.io.File if the class path resource resides in the file system, but not for resources in a JAR. Always supports resolution as URL.
翻譯過來就是:
類路徑資源的資源實現。使用給定的ClassLoader或給定的類來載入資源。
如果類路徑資源駐留在檔案系統中,則支援解析為 java.io.File,如果是JAR中的資源則不支援。始終支援解析為URL。
三、Jar 中資原始檔
上面也提到了,如果靜態資原始檔在檔案系統裡,則支援解析為 java.io.File
,程式是能正常工作的。
到專案打包成 Jar
包放到伺服器上執行就報找不到資源的錯誤了!
解決法案是:不獲取 java.io.File
物件,而是直接獲取輸入流
:
Resource resource = new ClassPathResource("ueditorConfig.json" );
BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
說明:構造得到 resource
物件之後直接獲取其輸入流 resource.getInputStream()
。