Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing ZipOutputStream

Tags:

java

zip

I'm a bit confused. I know that an empty zip is not legal. But what about this sample snippet:

ZipOutputStream zos = null; 
try
{
    zos = new ZipOutputStream(new FileOutputStream("..."));
    //
    //..
    //
}
finally
{
    zos.close();
}

If no zip entries had been added for some reason (possibly exceptional situation) then the following exception will be thrown on close attempt:

Exception in thread "main" java.util.zip.ZipException: ZIP file must have at least one entry
    at java.util.zip.ZipOutputStream.finish(ZipOutputStream.java:304)
    at java.util.zip.DeflaterOutputStream.close(DeflaterOutputStream.java:146)
    at java.util.zip.ZipOutputStream.close(ZipOutputStream.java:321)

In this situation what would be the cleanest way to close the stream?

Thanks...

like image 552
Lachezar Balev Avatar asked Jan 13 '11 15:01

Lachezar Balev


People also ask

What is zip close method?

zip. ZipFile. close() method closes the ZIP file. Closing this ZIP file will close all of the input streams previously returned by invocations of the getInputStream method.

What is ZipOutputStream in Java?

public class ZipOutputStream extends DeflaterOutputStream. This class implements an output stream filter for writing files in the ZIP file format. Includes support for both compressed and uncompressed entries.

How can I zip a file in Java?

Creating a zip archive for a single file is very easy, we need to create a ZipOutputStream object from the FileOutputStream object of destination file. Then we add a new ZipEntry to the ZipOutputStream and use FileInputStream to read the source file to ZipOutputStream object.


1 Answers

You should close the FileOutputStream, not the ZipOutputStream, because the former is what actually consumes system resources.

File zipFile = new File("/tmp/example.zip");
FileOutputStream fos = null;
try
{
   fos = new FileOutputStream(zipFile);
   ZipOutputStream zos = new ZipOutputStream(fos);

   // ...

   zos.close();
}
catch (IOException ex)
{
   // log/report exception, then delete the invalid file
   IOUtils.closeQuietly(fos);
   zipFile.delete();
}
finally
{
   IOUtils.closeQuietly(fos);
}

The IOUtils class is found in Jakarta Commons IO. Using it means that you don't have to deal with the possible-but-rarely-useful IOException that can be thrown by close().

like image 139
Anon Avatar answered Sep 20 '22 00:09

Anon