操作:
在项目resouces目录下存放文件,然后在代码中尝试获取,代码如下:
ClassPathResource resource = new ClassPathResource("XXX.cfg");File file = resource.getFile();复制代码
问题:
执行jar,项目运行,调用的时候会抛出如下异常:
Caused by: java.io.FileNotFoundException: class path resource [XXX.cfg] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/sunmnet/JetBrains/workspace/xxx/target/xxx-1.0-SNAPSHOT.jar!/BOOT-INF/classes!/XXX.cfg at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:215) ~[spring-core-4.3.12.RELEASE.jar!/:4.3.12.RELEASE] at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:53) ~[spring-core-4.3.12.RELEASE.jar!/:4.3.12.RELEASE] at hello.whz.Application.lambda$lookup$0(Application.java:30) [classes!/:1.0-SNAPSHOT] at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:732) [spring-boot-1.5.8.RELEASE.jar!/:1.5.8.RELEASE] ... 14 common frames omitted复制代码
原因:
项目打成jar包后,资源文件也存在于jar包中,文件的绝对路径是jar:file:/D:/sunmnet/JetBrains/workspace/xxx/target/xxx-1.0-SNAPSHOT.jar!/BOOT-INF/classes!/XXX.cfg
但在运行过程中,spring是不允许直接访问jar包内的文件的,所以会报错。
解决:
采用读取流的方式访问文件:
ClassPathResource resource = new ClassPathResource("application.yml");InputStream inputStream = resource.getInputStream();复制代码