Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access file in jar file?

Tags:

java

file

jar

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.

like image 772
LRFLEW Avatar asked Mar 02 '11 18:03

LRFLEW


People also ask

How do I access files inside a JAR?

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 ...

Can you view code from a JAR file?

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.


2 Answers

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.

like image 129
typo.pl Avatar answered Sep 30 '22 18:09

typo.pl


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")));
like image 43
Isaac Truett Avatar answered Sep 30 '22 17:09

Isaac Truett