简体   繁体   中英

classLoader.getResource doesn't work in jar file

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("com/x/y/z.cfg");
File file = new File(url.getPath());

This works when running jar file from Eclipse but not works when running in a jar file.

java.io.FileNotFoundException: file:\\C:\\Users\\nova\\Desktop\\Matcher.jar!\\c om\\x\\y\\z.cfg

This is not a duplicate. I've checked all other questions, no useful information.

When file is bundled inside the jar then it become byte stream instead of a normal File object.

Try

InputStream stram=getClass().getClassLoader().getResourceAsStream(relativePath);

More Tutorial...

Read similar post here and here

You can't create a File instance, because the only file you have is the JAR. That's why getResource() returns URL. You can get stream by using URL.openStream() method to read contents.

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