Opening and extracting Zip files in java - It's there for a while, but I just found out html

Opening and extracting Zip files in java – It’s there for a while, but I just found out

A while ago I found out that it was possible to open Zip files with Java. Just open a regular java.io.File and pass it to the java.util.zip.ZipFile constructor.
It is possible for a long time (at least since version 1.3), but I didn’t expect this kind of functionality in an SDK. I was looking for a library to do it when a javadoc page from Sun showed up.

After analysis of that page I came up with a small piece of code. Again no rocket science, but it can save you some time and when I have to do something with zip files I just search for this blog 😉
I created an application that uses xml files. Those xml files can be uploaded, but they can grow very big. The largest file I had to handle was about 83MB. Internet is fast but you still have to wait for these file sizes to be uploaded. A solution is zipping the file and let the server extract it.


public void extractFile(){
  File file = new File("c:\\temp\\ZipFileWithManyFiles.zip");
  ZipFile zipFile = new ZipFile(file);
  Enumeration<? extends ZipEntry> enumeration = zipFile.entries();
  while (enumeration.hasMoreElements()) {
    ZipEntry zipEntry = enumeration.nextElement();
    String zipFileName = zipEntry.getName();

    InputStream inputStream = zipFile.getInputStream(zipEntry);
    OutputStream out = new FileOutputStream("c:\\temp\\extracted\\" + zipFileName);
    writeInputStreamToOutputStream(inputStream, out);
    out.close();
    inputStream.close();
  }
}

private void writeInputStreamToOutputStream(InputStream inputStream, OutputStream outthrows IOException {
    // Transfer bytes from the ZIP file to the output file
    byte[] buf = new byte[1024];
    int len;
    while ((len = inputStream.read(buf)) 0) {
        out.write(buf, 0, len);
    }
}

A ZipFile is not a File when you follow the Object Oriented inheritance rules, that’s a bit strange, but I can live with it. Once you instansiated the ZipFile you can call the entries() method and you will receive a list with all files in the archive.
You can get an InputStream for every entry, note that you have to get the InputStream from ZipFile, not ZipEntry.
To write the InputStream to an OutputStream I wrote a small method (does anyone know a better solution?, my method doesn’t feel right). And finally you have to close the out and inputStream.

The ZipFile classes are very useful, the API is a bit odd, but does the trick.

2 Comments

  1. p3t0r November 20, 2007
  2. bloid November 20, 2007