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...
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.
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.
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With