FileNotFoundException: class path resource [static/download/template.xlsx] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/.jar!/BOOT-INF/classes!/static/download/template.xlsx
报错的代码
File file = ResourceUtils.getFile("classpath:static/download/template.xlsx");
ResourceUtils.getFile源码如下:
而resourceUrl.getProtocol() = “jar” 所以报错
这是因为springboot打成jar包运行,Resource下的文件是存在于jar这个文件里面,在磁盘上是没有真实路径存在的,它其实是位于jar内部的一个路径。所以通过ResourceUtils.getFile或者this.getClass().getResource("")方法无法正确获取文件。
解决办法:以文件流的方式读取jar中文件
将文档放在项目外,应用可以读取到的一个固定目录。按正常的方式读取即可,但可维护性比较差,很容易被误操作丢失。
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource resource = resolver.getResource("static/download/template.xlsx");
InputStream inputStream = resource.getInputStream();
ClassPathResource classPathResource = new ClassPathResource("static/download/template.xlsx");
InputStream inputStream1 = classPathResource.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(path)));