SpringBoot 如何讀取classpath下的文件
開發過程中,必不可少的需要讀取文件,對于打包方式的不同,還會存在一些坑,比如以jar包方式部署時,文件都存在于jar包中,某些讀取方式在開發工程中都可行,但是打包后,由于文件被保存在jar中,會導致讀取失敗。
這時就需要通過類加載器讀取文件,類加載器可以讀取jar包中的class類當然也可以讀取jar包中的文件。
// 方法1:獲取文件或流this.getClass().getResource('/')+fileName;this.getClass().getResourceAsStream(failName);// 方法2:獲取文件File file = org.springframework.util.ResourceUtils.getFile('classpath:test.txt');// 方法3:獲取文件或流ClassPathResource classPathResource = new ClassPathResource('test.txt');classPathResource .getFile();classPathResource .getInputStream();// >>>>>>>>>>>>>>>> 下面方法可以讀取jar包下文件假設resources目錄下有一個test.txt文件,首先獲得當前的類加載器,通過類加載器讀取文件。// 方法1InputStream io = Thread.currentThread().getContextClassLoader().getResourceAsStream('test.txt');// 方法2InputStream io = getClass().getClassLoader().getResourceAsStream('test.txt');
注意:
Spring工具類會對classpath路徑做處理,類加載器不會對classpath做處理,因此使用類加載器讀取文件,路徑中不要添加classpath
SpringBoot項目打包成jar后獲取classpath下文件失敗公司的一個SpringBoot項目中,有需要下載文件模板的需求,按理來說分布式項目文件都應該上傳到文件服務器,但是由于文件不是太多于是就放在了classpath下,在本地開發的時候發現都能正常下載文件,但是打包成jar上傳到Linxu測試環境上就報錯,找不到classpath路徑。
原因原因是項目打包后Spring試圖訪問文件系統路徑,但無法訪問JAR包中的路徑。我們使用ResourceUtils.getFile('classpath:');這樣的方式是獲取不到路徑的。
解決方案我們雖然不能直接獲取文件資源路徑,但是我們可以通過流的方式讀取資源,拿到輸入流過后我們就可以對其做操作了。關鍵代碼如下:
ClassPathResource resource = new ClassPathResource('staticpatterntest.txt'); // static/pattern下的 test.txt文件InputStream in = resource.getInputStream(); //獲取文件輸入流示例Demo
1. 在static下新建pattern目錄,并新建一個名為 test.txt的文件
2. 新建DownloadController.java
代碼如下:
package com.example.jekins.controller;import org.springframework.core.io.ClassPathResource;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.URLEncoder;@RestControllerpublic class DownloadController { @GetMapping('/download/pattern') public void downloadPattern(HttpServletRequest request, HttpServletResponse response){System.out.println('開始下載文件.....');ClassPathResource resource = new ClassPathResource('staticpatterntest.txt');try {//獲取文件輸入流 InputStream in = resource.getInputStream(); //下載文件 downFile('test文件.txt',request,response,in);} catch (IOException e) { e.printStackTrace();} } /** * 下載文件 * @param fileName 下載文件名稱 * @param response 響應 * @throws IOException 異常 */ public static void downFile(String fileName,HttpServletRequest request,HttpServletResponse response,InputStream in) throws IOException {//輸出流自動關閉,java1.7新特性try(OutputStream os = response.getOutputStream()) { fileName = URLEncoder.encode(fileName, 'UTF-8'); response.reset(); response.setHeader('Content-Disposition', 'attachment; filename=' + fileName); response.setContentType('application/octet-stream; charset=UTF-8'); byte[] b = new byte[in.available()]; in.read(b); os.write(b); os.flush();} catch (Exception e) { System.out.println('fileName=' + fileName); e.printStackTrace();} finally { if (in != null) {in.close(); }} }}
3. 測試 使用Maven工具把項目打成jar包
在target下生成了jar包
進入jar包所在的文件夾,按住shift并右擊,點擊在此處打開命令行窗口。輸入命令啟動項目 java -jar 打包后的文件
我設置的端口是8086,瀏覽器地址欄輸入http://127.0.0.1:8086/download/pattern
此時我們可以卡看到test.txt文件下載成功
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
