美文网首页
SpringBoot构建成jar包,读取不到resources目

SpringBoot构建成jar包,读取不到resources目

作者: Lord丶轩莫言弃 | 来源:发表于2019-04-10 13:59 被阅读0次

SpringBoot项目构建成jar运行后,如何正确读取resource下的文件

  1. 项目中使用poi根据模板导出excel功能,模板路径全部放在resource目录下面的templates中,目录结构如下图:


    image.png
  2. 本地开发环境测试正常,获取模板路径工具类如下:
public class TemplateFileUtil {
    public static FileInputStream getTemplates(String tempName) throws IOException {
        return new FileInputStream(new ClassPathResource("templates/" + tempName).getFile());
    }
}
  1. 生成环境事故,执行导出,找不到模板,修改获取模板路径工具类如下:
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);
    }
}
  1. 至此,导出功能正常。此解决方案参考资料如下:
    @growithus
    原文地址:https://blog.csdn.net/hero272285642/article/details/85119778

相关文章

网友评论

      本文标题:SpringBoot构建成jar包,读取不到resources目

      本文链接:https://www.haomeiwen.com/subject/oeeniqtx.html