Java and zip files

I’ve just spent a day debugging what at first appeared to be a permissions problem. Im using the jakarta commons file upload with a tomcat / spring setup to allow users to upload zip files, which are then unpacked and the contents are processed into a database. Obviously using a zip should make it easier to upload multiple files and directory structures.

What was happening is that the directory entries I expected to be in the zip werent being created, so none of the files could be written when it was unpacked. Eventually i discovered that the problem was related to how different tools create zip files. I use winrar, which creates a seperate entry for a directory, as luck would have it the tool my client was using doesnt.

So, if you are writing java code to unpack zip files you will be better off doing something like this :

Enumeration entries = zip.entries();

    while (entries.hasMoreElements())
    {
        ZipEntry zipEntry = (ZipEntry) entries.nextElement();
        File file = new File(outputDirectory, zipEntry.getName());

        // check the parent of this entry to see if it exists
        if(!file.getParentFile().exists())
        {
            file.getParentFile().mkdir();
        }

	InputStream is = zip.getInputStream(zipEntry);
        FileOutputStream fos = new FileOutputStream(file);

	while (is.available() > 0)
        {
            fos.write(is.read());
        }

	fos.close();
	is.close();
}

rather than just checking if zipEntry.isDirectory() and then doing a mkdir.

Of course its wise to do both, because the zip may contain empty directories and you might rely on them being present later on.

Leave a Reply

Your email address will not be published. Required fields are marked *