簡體   English   中英

在java中解壓縮jar的最簡單方法

[英]Easiest way to unpack a jar in java

基本上,我有一個jar文件,我想從junit測試解壓縮到一個特定的文件夾。

最簡單的方法是什么? 如果有必要,我願意使用免費的第三方圖書館。

您可以使用java.util.jar.JarFile迭代文件中的條目,通過其InputStream提取每個條目並將數據寫入外部文件。 Apache Commons IO提供了實用程序,使其不那么笨拙。

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();
    }
}

Jar基本上是使用ZIP算法壓縮的,所以你可以使用winzip或winrar來提取。

如果您正在尋找程序化方式,那么第一個答案更正確。

從命令行輸入jar xf foo.jarunzip foo.jar

使用Ant 解壓縮任務

這是我在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()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM