Spring Boot 讀取靜態資源文件

一、需求場景

有時候我們需要在項目中使用一些靜態資源文件,比如城市信息文件 ueditorConfig.json,在項目啓動後讀取其中的數據並初始化寫進數據庫中。

二、實現

靜態資源文件 ueditorConfig.json 放在 src/main/resources 目錄下

使用 Spring 的 ClassPathResource 來實現 :

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()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章