Kissaki
Kissaki

Reputation: 9237

Accessing files packaged into a jar file

I created a jar file with a runnable compiled class and some template files (text). I now want to use the text files packaged into the jar for distribution in the application as File objects.

I tried to just use relative paths which did not work. How do I get a File object pointing to a text file which is in the jar?

Is there a way to do this so it will work both when running the unpackaged class files and from a jar with the same code, or will I need to use separate functions?

Upvotes: 3

Views: 2442

Answers (2)

Buhake Sindi
Buhake Sindi

Reputation: 89199

If you are using the JAR within your application, then Class.getResourceAsStream(String) will do.

Alternatively, if you're using Servlet, then ServletContext.getResourceAsStream(String) will also do.

These 2 methods returns an InputStream (of your resource data) and not your File object as you rightfully want.

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240966

from inside jar you can use it like Class.getResourceAsStream(String), or something similar.

from out side its not the file its jar so you will have to extract it in order to actually use inside file

Upvotes: 5

Related Questions