Basically, I have a jar file that i want to unzip to a specific folder from a junit test.
What is the easiest way to do this? I am willing to use a free third party
ZipInputStream in = null;
OutputStream out = null;
try {
// Open the jar file
String inFilename = "infile.jar";
in = new ZipInputStream(new FileInputStream(inFilename));
// Get the first entry
ZipEntry entry = in.getNextEntry();
// Open the output file
String outFilename = "o";
out = new FileOutputStream(outFilename);
// Transfer bytes from the ZIP file to the output file
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (IOException e) {
// Manage exception
} finally {
// Close the streams
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
}
From command line type jar xf foo.jar
or unzip foo.jar
Use the Ant unzip task.
You could use java.util.jar.JarFile
to iterate over the entries in the file, extracting each one via its InputStream
and writing the data out to an external File. Apache Commons IO provides utilities to make this a bit less clumsy.
Jar is basically zipped using ZIP algorithm, so you can use winzip or winrar to extract.
If you are looking for programmatic way then the first answer is more correct.
Here's my version in Scala, would be the same in Java, that unpacks into separate files and directories:
import java.io.{BufferedInputStream, BufferedOutputStream, ByteArrayInputStream}
import java.io.{File, FileInputStream, FileOutputStream}
import java.util.jar._
def unpackJar(jar: File, target: File): Seq[File] = {
val b = Seq.newBuilder[File]
val in = new JarInputStream(new BufferedInputStream(new FileInputStream(jar)))
try while ({
val entry: JarEntry = in.getNextJarEntry
(entry != null) && {
val f = new File(target, entry.getName)
if (entry.isDirectory) {
f.mkdirs()
} else {
val bs = new BufferedOutputStream(new FileOutputStream(f))
try {
val arr = new Array[Byte](1024)
while ({
val sz = in.read(arr, 0, 1024)
(sz > 0) && { bs.write(arr, 0, sz); true }
}) ()
} finally {
bs.close()
}
}
b += f
true
}
}) () finally {
in.close()
}
b.result()
}