Unable to unzip zip file created with java

1.2k views Asked by At

I have a list of files from different locations. I create a zip file using the following the code which works without error. But when I try to unzip the file in Windows using Extract All it fails seeing unable to find any bytes, yet if I double click into the zip file itself with Windows Explorer I can see the files and individual ones can be opened and contains the correct data

       ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
        for (File next : files)
        {
            ZipEntry zipEntry = new ZipEntry(next.getName());
            zos.putNextEntry(zipEntry);
            FileInputStream in = new FileInputStream(next);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0)
            {
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            in.close();
        }
        zos.close();
1

There are 1 answers

0
Dodd10x On

This may or may not be related but I've found using fixed byte length can lead to a loss of new line characters.

This may help:

final byte[] newLine = System.getProperty(
        "line.separator").getBytes("UTF-8");

while ((line = in.readLine()) != null) 
        final byte[] buffer = line.getBytes("UTF-8");
        out.write(buffer, 0, buffer.length);
        out.write(newLine, 0, newLine.length);
}