ClassPathResource不能正常获取文件资源

Posted by SFHJavaer on 2025-04-01
Estimated Reading Time 1 Minutes
Words 231 In Total
Viewed Times

今天在线上部署jar包之后,发现在本地正常的ClassPathResource不能正常获取文件了,提示文件找不到

1
2
Resource resource = new ClassPathResource("data/test/txt");  
String path = resource.getFile().getPath());
1
2
Caused by: java.io.FileNotFoundException: class path resource [application.yml] 
cannot be resolved to absolute file path because it does not reside in the file system:

new ClassPathResource方法获取相对路径是没问题的,这个报错其实是getFile方法报出的

原因是在jar里,返回的是一个Jar协议地址:jar:file:/xxx/xx.jar!/xxxx

getFile源码:

1
2
3
4
5
6
7
8
9
10
11
12
public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {
Assert.notNull(resourceUrl, "Resource URL must not be null");
if (!"file".equals(resourceUrl.getProtocol())) {
throw new FileNotFoundException(description + " cannot be resolved to absolute file path because it does not reside in the file system: " + resourceUrl);
} else {
try {
return new File(toURI(resourceUrl).getSchemeSpecificPart());
} catch (URISyntaxException var3) {
return new File(resourceUrl.getFile());
}
}
}

“file”.equals(resourceUrl.getProtocol()协议不相等,直接报错,所以平时开发禁止使用getFile。


如果您喜欢此博客或发现它对您有用,则欢迎对此发表评论。 也欢迎您共享此博客,以便更多人可以参与。 如果博客中使用的图像侵犯了您的版权,请与作者联系以将其删除。 谢谢 !