在java中解压缩jar的最简单方法

时间:2009-08-19 18:03:44

标签: java jar

基本上,我有一个jar文件,我想从junit测试解压缩到特定的文件夹。

最简单的方法是什么? 如果有必要,我愿意使用免费的第三方图书馆。

6 个答案:

答案 0 :(得分:6)

您可以使用java.util.jar.JarFile迭代文件中的条目,通过其InputStream提取每个条目并将数据写入外部文件。 Apache Commons IO提供了一些实用工具,使其不那么笨拙。

答案 1 :(得分: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();
    }
}

答案 2 :(得分:2)

Jar基本上使用ZIP算法压缩,因此您可以使用winzip或winrar来提取。

如果您正在寻找程序化方式,那么第一个答案就更正确了。

答案 3 :(得分:1)

从命令行输入jar xf foo.jarunzip foo.jar

答案 4 :(得分:1)

使用Ant unzip task

答案 5 :(得分:0)

这是我在Scala中使用的版本,在Java中也是如此,它将解压缩成单独的文件和目录:

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()
}
相关问题