2009-08-19 58 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(); 
    } 
}