Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting a file from the currently running JAR through code

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.

like image 370
Konstantin Avatar asked Jul 13 '12 14:07

Konstantin


People also ask

Can we extract files from jar?

The jar-file argument is the filename (or path and filename) of the JAR file from which to extract files. archived-file(s) is an optional argument consisting of a space-separated list of the files to be extracted from the archive. If this argument is not present, the Jar tool will extract all the files in the archive.

How do I unpack an executable JAR file?

Type in jar xf followed by a space followed by the name of the JAR file. This is the command to extract a JAR file. For example, to extract a JAR file called "minecraft", you would type in jar xf minecraft. jar .

How do I open a JAR file with code?

Hi, 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

File file = new File("newname.ext");
if (!file.exists()) {
     InputStream link = (getClass().getResourceAsStream("/path/resources/filename.ext"));
     Files.copy(link, file.getAbsoluteFile().toPath());
}
like image 75
Renato Avatar answered Sep 19 '22 15:09

Renato


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.

like image 44
Dave Newton Avatar answered Sep 20 '22 15:09

Dave Newton