14

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.

Konstantin
  • 2,575
  • 3
  • 20
  • 23

3 Answers3

22
File file = new File("newname.ext");
if (!file.exists()) {
     InputStream link = (getClass().getResourceAsStream("/path/resources/filename.ext"));
     Files.copy(link, file.getAbsoluteFile().toPath());
}
bummi
  • 26,839
  • 13
  • 60
  • 97
Renato
  • 309
  • 3
  • 2
  • Note that some of Files.copy implementation (java.nio.file.Files) does not close the input stream -> possible memory leak. – Vity Jan 25 '18 at 07:24
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.

milchreis
  • 65
  • 7
Dave Newton
  • 156,572
  • 25
  • 250
  • 300
  • 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 ". – jarnbjo Jul 13 '12 at 14:28
  • @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. – Dave Newton Jul 13 '12 at 14:32
  • 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(); – Per Lindberg Oct 26 '16 at 14:23
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)?

Community
  • 1
  • 1
GuruKulki
  • 25,118
  • 47
  • 138
  • 197