ClassPathResource resource = new ClassPathResource(publicKeyCer);
File file = null;
try {
file = resource.getFile();
} catch (IOException e) {
e.printStackTrace();
}
InputStream inStream = new FileInputStream( file.getPath());
一、需求場景
有時候我們需要在項目中使用一些靜態資源文件,比如城市信息文件 countries.xml,在項目啟動后讀取其中的數據並初始化寫進數據庫中。
二、實現
靜態資源文件 countries.xml 放在 src/main/resources 目錄下
使用 Spring 的 ClassPathResource 來實現 :
Resource resource = new ClassPathResource("countries.xml");
File file = resource.getFile();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
1
2
3
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.
1
2
3
翻譯過來就是:
類路徑資源的資源實現。使用給定的ClassLoader或給定的類來加載資源。
如果類路徑資源駐留在文件系統中,則支持解析為 java.io.File,如果是JAR中的資源則不支持。始終支持解析為URL。
1
2
3
三、Jar 中資源文件
上面也提到了,如果靜態資源文件在文件系統里,則支持解析為 java.io.File,程序是能正常工作的。
到項目打包成 Jar 包放到服務器上運行就報找不到資源的錯誤了!
解決法案是:不獲取 java.io.File 對象,而是直接獲取輸入流:
Resource resource = new ClassPathResource("countries.xml");
BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
1
2
說明:構造得到 resource 對象之后直接獲取其輸入流 resource.getInputStream()。
四、附錄
Spring Boot access static resources missing scr/main/resources
Classpath resource not found when running as jar