3

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 library if it's necessary.

pbreault
  • 14,176
  • 18
  • 45
  • 38

6 Answers6

6

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
4
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();
    }
}
Community
  • 1
  • 1
KingInk
  • 536
  • 1
  • 3
  • 7
2

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.

jatanp
  • 3,982
  • 4
  • 40
  • 46
1

From command line type jar xf foo.jar or unzip foo.jar

Clinton Bosch
  • 2,497
  • 4
  • 32
  • 46
1

Use the Ant unzip task.

martin clayton
  • 76,436
  • 32
  • 213
  • 198
Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
0

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()
}
0__
  • 66,707
  • 21
  • 171
  • 266