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();