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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用Spring Boot时,可能会出现打成JAR运行后无法读取resources里的文件问题。这是因为在JAR包中,资源文件会被打包到一个压缩文件中,而不是一个文件夹中。 解决这个问题有几种方法: 1. 使用Classloader获取资源 可以使用Java的Classloader获取JAR包中的资源。这种方法可行,但较繁琐。 举个例子: ```java ClassLoader classLoader = getClass().getClassLoader(); InputStream inputStream = classLoader.getResourceAsStream("file.txt"); ``` 这样做可以读取位于JAR包中的file.txt文件。 2. 使用Spring提供的ResourceLoader Spring提供了ResourceLoader来处理此问题。我们可以注入ResourceLoader并使用它读取资源。 举个例子: ```java @Autowired private ResourceLoader resourceLoader; public void readFile() throws IOException { Resource resource = resourceLoader.getResource("classpath:file.txt"); InputStream inputStream = resource.getInputStream(); } ``` 这个方法还可以处理其他类型的资源,例如网络资源等。 3. 使用FileSystemResource 我们可以使用FileSystemResource来读取文件。这种方法需要JAR包解压到文件夹中,然后使用FileSystemResource来读取文件。 ```java Resource resource = new FileSystemResource(file.txt); InputStream inputStream = resource.getInputStream(); ``` 但是这种方法会使JAR包无法单独使用。 总之,以上三种方法都可以解决打成JAR运行后无法读取resources里的文件问题,我们可以根据实际情况选择其中一种方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值