ResourceUtils.getFile 獲取檔案 獲取jar包中的資原始檔
阿新 • • 發佈:2018-12-14
摘要:通過Spring工具類獲取classpath下的檔案資源;獲取jar包中的資原始檔
1. web專案下classpath檔案獲取
方法(1)File resourcefile = ResourceUtils.getFile("classpath:application.properties");
方法(2) Resource resourcefile = new ClassPathResource("application.properties");
獲取檔案:resourcefile .getFile() / 獲取檔案流:resourcefile .getInputStream();
2. 獲取web專案jar包中檔案:
方法(1) :Resource fileRource = new ClassPathResource("application.properties");
獲取檔案流:fileRource.getInputStream();
方法(2) :Thread.currentThread().classLoader().getResourceAsstream()
private String readFileByLines(String filePath) throws Exception { StringBuffer str = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(findClassLoader().getResourceAsStream(filePath) , "UTF-8")); String tempString = null; // 一次讀入一行,直到讀入null為檔案結束 while ((tempString = reader.readLine()) != null) { str = str.append(" " + tempString); } reader.close(); } catch (IOException e) { e.printStackTrace(); throw e; } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } return str.toString(); } /** * 配合api讀取linux環境下jar包中的檔案路徑 * @return */ private ClassLoader findClassLoader(){ ClassLoader loader = Thread.currentThread().getContextClassLoader(); if(loader==null){ loader = ClassLoader.getSystemClassLoader(); } return loader; }
Class.getResource("")獲取的是相對於當前類的相對路徑
Class.getResource("/")獲取的是classpath的根路徑
ClassLoader.getResource("")獲取的是classpath的根路徑