0

我在创建存档时遇到问题 - 尝试解压缩 Windows 时显示存在错误。是代码的问题吗?

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

1 回答 1

2

我会写下我的评论作为答案,因为它解决了问题。

所有流 ( InputStream, OutputStream) 都应使用它们的close()方法关闭,以确保数据已被写出并且没有剩余的打开处理程序。

在 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();
}
于 2012-07-04T11:56:41.857 回答