正確讀取resources目錄下的檔案
阿新 • • 發佈:2018-12-14
問題描述:本地可以正常讀取areacode.json檔案,打成jar包在測試環境找不到該檔案。
問題程式碼:
static { StringBuffer strbuffer = new StringBuffer(); try { String path = Thread.currentThread().getContextClassLoader().getResource("areacode.json").getPath(); File myFile = new File(path);if (myFile.exists()) { InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(path), "UTF-8"); BufferedReader in = new BufferedReader(inputStreamReader); String str =null; while ((str = in.readLine()) != null) { strbuffer.append(str); } in.close(); } }catch (Exception e) { e.getStackTrace(); } }
解決方案:
static { StringBuffer strbuffer = new StringBuffer(); try { InputStream stream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("areacode.json"); BufferedReader in= new BufferedReader(new InputStreamReader(stream, "UTF-8")); String str = null; while ((str = in.readLine()) != null) { strbuffer.append(str); } logger.info("【地區轉換工具類】 檔案輸入流獲取完成, 輸入流關閉!"); in.close(); } catch (Exception e) { e.getStackTrace(); } }
參考來自:https://blog.csdn.net/baidu_23275675/article/details/82622577
一般方法:
Properties pps = new Properties(); File file = ResourceUtils.getFile("classpath:defult.properties"); pps.load(new FileReader(file));
此時打包成jar執行時會報錯: java.io.FileNotFoundException
• 在除錯過程中,檔案是真實存在於磁碟的某個目錄。此時通過獲取檔案路徑,是可以正常讀取的,因為檔案確實存在。
• 而打包成jar以後,實際上檔案是存在於jar這個檔案裡面的資原始檔,在磁碟是沒有真實路徑的。所以通過ResourceUtils.getFile或者this.getClass().getResource("")方法無法正確獲取檔案。
正確方法:
•採用流的方式進行處理,同時讀取流時設定編碼utf-8
•使用InputStream inputStream=this.getClass().getResourceAsStream("") 會指定要載入的資源路徑與當前類所在包的路徑一致。因此能正常讀取檔案。
Properties pps = new Properties(); InputStream stream = getClass() .getClassLoader() .getResourceAsStream("defult.properties"); BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8")); pps.load(br);