簡體   English   中英

java zip存檔損壞

[英]java zip archive damaged

我對創建的存檔有問題 - 當嘗試解壓縮窗口時顯示存在錯誤。 這是代碼問題嗎?

File dir = new File("M:\\SPOT/netbeanstest/TEST/PDF");
    String archiveName = "test.zip";

    byte[] buf = new byte[1024];
    try {
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(
                archiveName));

        for (String s : dir.list()) {
            File toCompress = new File(dir, s);
            FileInputStream fis = new FileInputStream(toCompress);

            zos.putNextEntry(new ZipEntry(s));
            int len;
            while((len = fis.read(buf))>0){
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            fis.close();
        }

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

我會寫下我的評論作為答案,因為它解決了問題。

應使用close()方法關閉所有流( InputStreamOutputStream ),以確保數據已寫出並且沒有打開處理程序。

在finally塊中執行它是個好主意,如下所示:

ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(archiveName));

try {
    for (String s : dir.list()) {
        File toCompress = new File(dir, s);
        FileInputStream fis = new FileInputStream(toCompress);

        try {
            zos.putNextEntry(new ZipEntry(s));
            int len;

            while((len = fis.read(buf))>0){
                zos.write(buf, 0, len);
            }
            zos.closeEntry();

        } finally {
            fis.close();
        }
    }
} finally {
    zos.close();
}

暫無
暫無

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

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