springboot项目打成jar包后无法获取static下的静态资源文件的问题分析

Springboot项目打成jar包后无法获取static下的静态资源文件的问题分析

springboot 后端项目 做某个功能时 需要读取根目录下的.doc文件,具体项目中路径如下

开始是通过绝对路径读取文档,在本地没有任何问题。
但是 讲项目打成jar包 部署到测试环境发现无论怎样都读取不到,然后在本地运行jar包出现同样的情况。

捕获异常:java.io.FileNotFoundException

[org.apache.ibatis.session.defaults.DefaultSqlSession@55b40849]
java.io.FileNotFoundException: class path resource [static/.doc] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:///target/-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/static/***.doc

原因:
此时运行中的Java程序其实是在读取jar包中的文件,直接使用下面的方式是不行的:

常见的获取路径写法:
//例子 比如文件路径 src\main\resources\static\***.doc
String path = this.getClass().getClassLoader().getResource("").getPath()+"/static/***.doc";
File file = new File(path);

在java中,如果应用打成jar包后,应用运行后需要读取本jar包之内的文件,更换写法:

通过类加载器的getResourceAsStream方法,让jar读取到自己的资源文件
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("static/***.doc");

例如:

public static File getFile(String filePath, String... ops) {
        File file;
        if (filePath.startsWith("classpath:")) {
            InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath.substring("classpath:".length()));
            try {
                if (ops != null && ops.length >= 2) {
                    file = File.createTempFile(ops[0], ops[1]);
                } else {
                    file = File.createTempFile("temp", ".classfile");
                }
                org.apache.commons.io.FileUtils.copyInputStreamToFile(is, file);
            } catch (IOException e) {
                file = null;
                log.error("获取类路径文件发生IO异常!");
            } finally {
                IOUtils.closeQuietly(is);
            }
        } else {
            file = new File(filePath);
        }
        return file;
    }
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值