失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > SpringBoot打成jar包后无法读取resources资源文件里文件路径的问题 cannot be reso

SpringBoot打成jar包后无法读取resources资源文件里文件路径的问题 cannot be reso

时间:2020-02-28 06:05:28

相关推荐

SpringBoot打成jar包后无法读取resources资源文件里文件路径的问题 cannot be reso

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是真实存在于磁盘上的某个目录, 此时通过newFile(文件路径)是可以正常读取的。

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

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

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打成jar包后无法读取resources资源文件里文件路径的问题 cannot be resolved to absolute file path because it does

如果觉得《SpringBoot打成jar包后无法读取resources资源文件里文件路径的问题 cannot be reso》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。