SpringBoot构建成jar包,读取不到resources目录下文件问题
SpringBoot项目构建成jar运行后,如何正确读取resource下的文件
项目中使用poi根据模板导出excel功能,模板路径全部放在resource目录下面的templates中,目录结构如下图:
本地开发环境测试正常,获取模板路径工具类如下:
public class TemplateFileUtil {public static FileInputStream getTemplates(String tempName) throws IOException {return new FileInputStream(new ClassPathResource("templates/" + tempName).getFile());}
}
生成环境事故,执行导出,找不到模板,修改获取模板路径工具类如下:
public class TemplateFileUtil {public static FileInputStream getTemplates(String tempName) throws IOException {ClassPathResource classPathResource = new ClassPathResource("templates/" + tempName);InputStream inputStream = classPathResource.getInputStream();// 生成目标文件File targetFile = File.createTempFile("template_export_copy", ".xls");try {FileUtils.copyInputStreamToFile(inputStream, targetFile);} finally {IOUtils.closeQuietly(inputStream);}return new FileInputStream(targetFile);}
}
至此,导出功能正常。此解决方案参考资料如下:
原文地址:https://blog.csdn.net/hero272285642/article/details/85119778