16

Are there any built-in methods I can use to allow users to extract a file from the currently running JAR and save it on their disk?

Thanks in advance.

3 Answers 3

22
File file = new File("newname.ext"); if (!file.exists()) { InputStream link = (getClass().getResourceAsStream("/path/resources/filename.ext")); Files.copy(link, file.getAbsoluteFile().toPath()); } 
Sign up to request clarification or add additional context in comments.

2 Comments

Note that some of Files.copy implementation (java.nio.file.Files) does not close the input stream -> possible memory leak.
I don't understand what getClass is supposed to be. Where does it come from and which class does it have to be?
10

Use getResourceAsStream (docs), you can do whatever you want with it after that.

For a two-liner you could use one of the Commons IO copy methods.

3 Comments

getResourceAsStream will give you access to any matching resource on the class path and not only a file withing the "currently running JAR", assuming that that is a JAR file executed with "java -jar <JAR-file>".
@jarnbjo Yep. And if the resource isn't properly packaged, that's possibly an issue, but given the question, I think the issue is much broader than needing it to come specifically from the "running jar", to the exclusion of all other resources packaged exactly the same.
Note that you may want to specify an absolute path to the file in the jar. And then any class can be used. Example: InputStream is = Object.class.getResource("/" + filename).openStream();
0

I am not sure whether you will get know from which jar your class is getting executed but you can try this to extract resources from jar : How to write a Java program which can extract a JAR file and store its data in specified directory (location)?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.