springboot讀取resources文件夾下的文件

  • 2019 年 12 月 5 日
  • 筆記

第一種方法

File file =  ResourceUtils.getFile("classpath:template.docx");  //獲取文件的相對路徑  可在控制台列印查看輸出結果  String filePath = ResourceUtils.getFile("classpath:template.docx").getPath();

第二種方法

//直接將目標文件讀成inputstream  this指當前類的實例對象  InputStream ins = this.getClass().getClassLoader().getResourceAsStream("template.docx");  File file = new File(ins);

只是適合打成war下使用的,有一些在eclipse或者Idea下使用時正常的,但是一打成jar就會出現FileNotFoundException 了。比如:在開發中,我們需要獲取類路徑下的某個資源文件,一般我們都會使用ResourceUtils工具類,快捷方便,但是在打包的時候,會出現一些異常 解決方案也很簡單,換一個工具類就可以了:

 ClassPathResource classPathResource =  new ClassPathResource("template.docx");   InputStream is = classPathResource.getInputStream();