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));
        }
    }

参考

https://blog.csdn.net/zhuyu19911016520/article/details/98071242

https://blog.csdn.net/liangcha007/article/details/88526181

posted @ 2019-10-24 09:37  qingshanli  阅读(11820)  评论(0编辑  收藏  举报