gpt4 book ai didi

java - 关闭 ZipOutputStream

转载 作者:搜寻专家 更新时间:2023-10-30 21:27:07 27 4
gpt4 key购买 nike

我有点困惑。我知道空 zip 是不合法的。但是这个示例片段呢:

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

如果由于某种原因(可能是特殊情况)没有添加 zip 条目,则在关闭尝试时将抛出以下异常:

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)

在这种情况下,关闭流的最简洁方法是什么?

谢谢...

最佳答案

您应该关闭 FileOutputStream,而不是 ZipOutputStream,因为前者才是真正消耗系统资源的。

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);
}

IOUtils 类位于 Jakarta Commons IO 中.使用它意味着您不必处理可能由 close() 抛出但很少有用的 IOException

关于java - 关闭 ZipOutputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4681459/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com