Springboot 項目讀取Resources目錄下的文件(推薦)
需求描述:企業開發過程中,經常需要將一些靜態文本數據放到Resources目錄下,項目啟動時或者程序運行中,需要讀取這些文件。
讀取Resources目錄下文件的方法
/** * @Description: 讀取resources 目錄下的文件 * @Author: ljj * @CreateDate: 2020/11/3 17:20 * @UpdateUser: * @UpdateDate: * @UpdateReakem * @param filePath * @Return: java.lang.String **/ public static String getContent(String filePath){ String res = ''; if(StringUtils.isEmpty(filePath)){ log.info('文件路徑不能為空'); return res; } try { Resource resource = new ClassPathResource(filePath); BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream(),'UTF-8')); StringBuffer sb = new StringBuffer(); String str = ''; while((str=br.readLine())!=null) {sb.append(str); } res = sb.toString(); } catch (Exception e) { log.info('讀取文件{}時發生異常',filePath); e.printStackTrace(); } return res; }
需要調用時:
String Content = FileUtils.getContent('testData/網元拓撲1.json');
注意:testData 路徑前面沒有'/'
到此這篇關于Springboot 項目讀取Resources目錄下的文件的文章就介紹到這了,更多相關Springboot讀取Resources文件內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
