SpringBoot项目打成jar后读取resource下的文件

image.png

需求是提供一个下载文件模版的接口,本地跑的没啥问题,但是打成jar就不行了,拿到的是一堆包含!的路径。
以下方法在本地还是打成jar都行:

 String filename = "templates/template.xlsx";
    ClassPathResource classPathResource = new ClassPathResource("templates/template.xlsx");
    InputStream inputStream = classPathResource.getInputStream();

补充:
不管是用ClassPathResource还是ClassLoader,读取jar里面的文件,我们只能用流去读取,不能用file,文件肯定要牵扯路径。

BufferedReader in = new BufferedReader(new InputStreamReader(AuditConstant.class.getClassLoader().getResourceAsStream("xxx")));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null){
    buffer.append(line);
}

评论

暂无评论