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

问题描述 投票:3回答:6

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

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

java jar
6个回答
6
投票

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


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
投票

Jar基本上是使用ZIP算法压缩的,所以你可以使用winzip或winrar来提取。

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


1
投票

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


1
投票

使用Ant unzip task


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()
}
© www.soinside.com 2019 - 2024. All rights reserved.