简体   繁体   中英

java zip archive damaged

I have a problem with a created archive - when trying to unzip windows shows that there's an error. Is it an issue with code?

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

I'll write write my comment down as an answer because it solved the problem.

All streams ( InputStream , OutputStream ) should be closed with their close() method to make sure that the data has been written out and no open handlers has left over.

It's a good idea to do it in a finally block, like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM