ClassLoader.getResource not working 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 a jar file from Eclipse, but does not work when running in a jar file.

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

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

+7
java eclipse
source share
2 answers

When a file enters the jar, it becomes a byte stream instead of the regular File object.

Try

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

More Tutorial ...

Read a similar message here and here.

+11
source share

You cannot create an instance of File because the only file you have is a JAR. This is why getResource () returns a URL. You can get the stream using the URL.openStream () method to read the content.

+1
source share

All Articles