Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

classLoader.getResource doesn't work in jar file

Tags:

java

eclipse

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.

like image 378
Insignificant Person Avatar asked Oct 31 '14 12:10

Insignificant Person


People also ask

What is the difference between Class getResource () and ClassLoader getResource ()?

Class. getResources would retrieve the resource by the classloader which load the object. While ClassLoader. getResource would retrieve the resource using the classloader specified.

What is ClassLoader getResource?

getResource() method finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code. The name of a resource is a '/'-separated path name that identifies the resource.


2 Answers

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

like image 195
Braj Avatar answered Oct 16 '22 16:10

Braj


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.

like image 34
McMonster Avatar answered Oct 16 '22 16:10

McMonster