简体   繁体   中英

ClassPathResource: File not found exception when running the jar

I've written a java code which looks like below

String readFile(String schemaFileName) throws IOException {
    ClassPathResource classPathResource = new ClassPathResource("abc/" + schemaFileName);
    return FileUtils.readFileToString(classPathResource.getFile(), StandardCharsets.UTF_8);
}

When I'm running from IntelliJ everything is working fine but when I deploy the app using created jar it gives following exception

Caused by: java.io.FileNotFoundException: class path resource [abc/myfile] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/my_application.jar!/BOOT-INF/classes!/abc/myfile
    at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:215) ~[spring-core-4.3.9.RELEASE.jar!/:4.3.9.RELEASE]

In my jar, I can see the directory

$ ll BOOT-INF/classes/abc/myfile
total 44
drwxrwxr-x 2 ganesh ganesh  4096 Jan 23 12:59 ./
drwxrwxr-x 3 ganesh ganesh  4096 Jan 23 12:59 ../
-rw-rw-r-- 1 ganesh ganesh 31735 Jan 23 12:59 myfile

What am I missing?

You need to use classpath*:my.config if your spring-context.xml and my.config files are in different jars

Also, make sure you are using resource.getInputStream() not resource.getFile() when loading from inside a jar file.

More details can be found here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM