Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java压缩文件已损坏_Java_Zip - Fatal编程技术网

java压缩文件已损坏

java压缩文件已损坏,java,zip,Java,Zip,我对创建的归档文件有问题-尝试解压缩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(

我对创建的归档文件有问题-尝试解压缩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();
    }

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

所有流(,)都应该用它们的方法关闭,以确保数据已经被写出来,并且没有留下任何打开的处理程序

最好在最后一块中进行,如下所示:

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

您应该在finally块中使用
zos.close()
关闭
ZipOutputStream
。我也面临同样的问题,您可以看看吗。我们将不胜感激