i want my jar file to access some files from itself. I know how to do this for BufferedImage
but this doesn't work for other files. All i want is to extract some zips from my jar. i made a class folder in eclipse, put the zips inside and used
public File getResFile(String name){
return new File(getClass().getResource(name).getFile());
}
to get the File
instance and extract it. it works fine in eclipse, but as soon as i export it to a jar it says
Exception in thread "main" java.io.FileNotFoundException: file:\C:\Users\DeLL\Desktop\BoxcraftClient\ClientInstaller.jar!\client.bxc (The filename, directory name, or volume label syntax is incorrect)
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(ZipFile.java:220)
at java.util.zip.ZipFile.<init>(ZipFile.java:150)
at java.util.zip.ZipFile.<init>(ZipFile.java:164)
at Launcher.install(Launcher.java:43)
at Launcher.main(Launcher.java:33)
Im working to fix this already something like 6 hours and can't find a solution. Please help!
Use one of these methods, from the class Class - getResource(java.lang.String) - getResourceAsStream(java.lang.String)
Warning: By default it loads the file from the location, where the
this.class
, is found in the package. So if using it from a classorg.organisation.project.App
, then the file need to be inside the jar in the directoryorg/organisation/project
. In case the file is located in the root, or some other directory, inside the jar, use the/
, in from of the file name. Like/data/names.json
.There is a reason why
getResource()
returns aURL
, and not aFile
, because the resource may not be a file, and since your code is packaged in the Jar file, it's not a file but a zip entry.The only safe way to read the content of the resource, is as an
InputStream
, either by callinggetResourceAsStream()
or by callingopenStream()
on the returnedURL
.first check your class path using java
System.out.println("classpath is: " + System.getProperty("java.class.path"));
to see if the classpath has your jar file.And then use the getclass().classloader.getResourceAsStream(name). See if the returned URL is correct. Call the method isFile() on the URL to check if the URL is actually a file. And then call the getFile() method.
Use Spring's PathMatchingResourcePatternResolver;
It will do the trick for both launching the package from an IDE or from the file system: