Skip to content
Advertisement

Access file in jar file?

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.

Advertisement

Answer

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.

Advertisement