zoukankan      html  css  js  c++  java
  • SpringBoot打成jar包后无法读取resources资源文件里文件路径的问题 cannot be resolved to absolute file path because it does

    SpringBoot打成jar包后无法读取resources资源文件

    在项目中做了一个支付功能, 需要引入第三方渠道的配置文件config.xml用来初始化文件证书, 将配置文件 config.xml 放到 resources 资源目录下。

    本地开发环境下能正常读取该文件, 但是在 Linux 环境下将项目打包成jar后运行会出现如下异常:

    java.io.FileNotFoundException: class path resource [static/config.xml] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/ROOT/xxx.jar!/BOOT-INF/lib/xxx-2.1.jar!/static/config.xml 
        at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:217) 
        at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:154) 
       ...

    因为在本地开发环境下, config.xml是真实存在于磁盘上的某个目录, 此时通过  new File(文件路径)  是可以正常读取的。

    但是在Linux下打包成jar后, 实际上config.xml是存在于jar里面的资源文件, 在磁盘上是没有真实路径存在的, 所以通过文件读取文件读取方式会报  java.io.FileNotFoundException 

    对此, Java API提供了一些方法, 可以通过I/O流的方式先获取这个文件流, 再将这个文件流写入到一个真实存在的指定磁盘路径, 这样我们就可以通过  new File() 读取文件的方式访问了.

    复制代码

        ApplicationHome applicationHome = new ApplicationHome(CcbImpl.class);
        //项目打包成jar包所在的根路径
        String rootPath = applicationHome.getSource().getParentFile().toString();
        String configFilePath = rootPath + "/xxx/xxx/config.xml";
        File configFile = new File(configFilePath);
        if (!configFile.exists()) {
            try {
             //获取类路径下的指定文件流
                InputStream in = this.getClass().getClassLoader().getResourceAsStream("static/config.xml");
                FileUtils.copyInputStreamToFile(Objects.requireNonNull(in, "config.xml文件找不到"), configFile);
            } catch (IOException e) {
                throw new IllegalArgumentException("保存文件证书失败->" + ExceptionUtils.getStackTraceAsString(e));
            }
        }

    复制代码

  • 相关阅读:
    阿里笔试题
    springboot-security-jwt
    java 面试架构篇
    java 面试题 mybatis 篇
    Java 多线程并发工具类
    java 面试题 高阶版
    给你的右键菜单添加“VScode”
    HTML重点知识点汇总
    HTML5知识点小结
    给博客园添加百度统计方法
  • 原文地址:https://www.cnblogs.com/suizhikuo/p/13413738.html
Copyright © 2011-2022 走看看