2009-08-19 27 views
3

基本上,我有一个jar文件,我想从junit测试中解压缩到特定文件夹。在java中解压jar的最简单方法

这样做最简单的方法是什么? 如果有必要,我愿意使用免费的第三方库。

回答

6

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

2

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

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

+1

在OP从junit测试执行的情况下不起作用。 – Chadwick 2009-08-19 18:10:15

1

从命令行类型jar xf foo.jarunzip foo.jar

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