I’m having a problem de-compressing a ZIP file using Java. The method is below.
The file structure is correct once the file is de-compressed, that means directories are fine inside the ZIP file, but the files output are of zero length.
I’ve checked the ZIP file, to see if the compression is correct, all correct there.
Please if anybody sees something I’ve missed …
public static void unzip ( File zipfile, File directory ) throws IOException {
ZipFile zip = new ZipFile ( zipfile );
Enumeration<? extends ZipEntry> entries = zip.entries ();
while ( entries.hasMoreElements () ) {
ZipEntry entry = entries.nextElement ();
File file = new File ( directory, entry.getName () );
if ( entry.isDirectory () ) {
file.mkdirs ();
}
else {
file.getParentFile ().mkdirs ();
ZipInputStream in = new ZipInputStream ( zip.getInputStream ( entry ) );
OutputStream out = new FileOutputStream ( file );
byte[] buffer = new byte[4096];
int readed = 0;
while ( ( readed = in.read ( buffer ) ) > 0 ) {
out.write ( buffer, 0, readed );
out.flush ();
}
out.close ();
in.close ();
}
}
zip.close ();
}
Something more… Apparently the method getInputStream ( entry ) is returning zero bytes, don’t know why exactly.
ZipFile already decompresses an entry’s data, there is no need to use a
ZipInputStreamas well.Instead of:
Use:
ZipInputStream can be used to uncompress ZIP files as well. The reason you are getting zero-length streams because with a ZipInputStream you need to call getNextEntry() to read the first file in the ZIP.