2012-04-12 150 views
3

我使用zt-zip由zeroturnaround,當我壓縮它,我試圖打開它,它說它已損壞。有任何想法嗎? ZipUtil.pack(new File("C:\\Users\\David"), new File(zipName)); http://pastie.org/3773634Java創建損壞的ZIP文件

+2

出於好奇,爲什麼不是java.util.zip? – 2012-04-12 11:40:05

+0

請發佈一個可重現的測試用例(可能將代碼放在pastebin.com或類似的地方)。沒有測試案例,我們不可能提供幫助。 – sleske 2012-04-12 11:40:24

+0

我一直在爲此掙扎很久。我決定使用這個。 – cheese5505 2012-04-12 11:40:55

回答

3

爲了讓你可以直接使用下面的Java類

進口java.util.zip.ZipFile中的壓縮文件;

// These are the files to include in the ZIP file 
String[] filenames = new String[]{"filename1", "filename2"}; 

// Create a buffer for reading the files 
byte[] buf = new byte[1024]; 

try { 
    // Create the ZIP file 
    String outFilename = "outfile.zip"; 
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename)); 

    // Compress the files 
    for (int i=0; i<filenames.length; i++) { 
     FileInputStream in = new FileInputStream(filenames[i]); 

     // Add ZIP entry to output stream. 
     out.putNextEntry(new ZipEntry(filenames[i])); 

     // Transfer bytes from the file to the ZIP file 
     int len; 
     while ((len = in.read(buf)) > 0) { 
      out.write(buf, 0, len); 
     } 

     // Complete the entry 
     out.closeEntry(); 
     in.close(); 
    } 

    // Complete the ZIP file 
    out.close(); 
} catch (IOException e) { 
} 
+0

我以前使用過類似的東西,但它總是給我一個損壞的文件。 – cheese5505 2012-04-12 11:42:31

+0

不管怎麼樣,我都會嘗試...... – cheese5505 2012-04-12 11:42:54

+0

我試過了,它創建了一個ZIP文件,但沒有添加任何東西。 – cheese5505 2012-04-12 11:47:06