classLoader.getResource doesn't work in jar fi

2020-05-26 14:24发布

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.

标签: java eclipse
2条回答
Bombasti
2楼-- · 2020-05-26 15:14

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

查看更多
▲ chillily
3楼-- · 2020-05-26 15:14

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.

查看更多
登录 后发表回答