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.
Class. getResources would retrieve the resource by the classloader which load the object. While ClassLoader. getResource would retrieve the resource using the classloader specified.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With