I need to be able to access a file stored in a compiled jar file. I have figured out how to add the file to the project, but how would I reference it in the code? How might I copy a file from the jar file to a location on the user's hard drive? I know there are dozens of ways to access a file (FileInputStream, FileReader, ect.), but I don't know how to look inside itself.
How To Open JAR Files. If you want to view each file in a non-executable jar file, you can do that with the help of a JAR file compatible compression/decompression software. Either WinRAR or 7-ZIP, any one of them is a good choice. After you have installed WinRAR or 7-ZIP, run it, open the file, and extract files in it ...
Jar files are archive files that contains of a lot of different java classes (files). You can use winzip/winrar to open the jar files and you can see those java classes in jar files. Typically you can use a Java decompiler to decompile the class file and look into the source code.
You could use something like this:
InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileFromJarFile);
If foo.txt was in the root of your JAR file, you'd use:
InputStream is = this.getClass().getClassLoader().getResourceAsStream("foo.txt");
assumes the class is in the same JAR file as the resource, I believe.
You can use getResource() to obtain a URL for a file on the classpath, or getResourceAsStream() to get an InputStream instead.
For example:
BufferedReader reader = new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream("foo.txt")));
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