gpt4 book ai didi

java - 为什么在这种情况下我必须以某种方式关闭 ZipOutputStream?

转载 作者:行者123 更新时间:2023-11-30 08:15:53 28 4
gpt4 key购买 nike

我有两个例子:

示例 1:

try (ByteArrayOutputStream baous = new ByteArrayOutputStream();     
FileOutputStream fouscrx = new FileOutputStream(new File(output, "example"))) {
try (ZipOutputStream zous = new ZipOutputStream(baous)) {
for (File file: files) {
try (FileInputStream fis = new FileInputStream(file)) {
ZipEntry zipEntry = new ZipEntry(file.getPath().substring(output.getPath().length() + 1));
zous.putNextEntry(zipEntry);
byte[] bytes = new byte[2048];
int length;
while ((length = fis.read(bytes)) >= 0) {
zous.write(bytes, 0, length);
}
zous.closeEntry();
}
}
}
baous.writeTo(fouscrx);
} catch (FileNotFoundException ex) {} catch (IOException ex) {}

示例 2:

try (ByteArrayOutputStream baous = new ByteArrayOutputStream();
ZipOutputStream zous = new ZipOutputStream(baous);
FileOutputStream fouscrx = new FileOutputStream(new File(output, "example"))) {
for (File file: files) {
try (FileInputStream fis = new FileInputStream(file)) {
ZipEntry zipEntry = new ZipEntry(file.getPath().substring(output.getPath().length() + 1));
zous.putNextEntry(zipEntry);
byte[] bytes = new byte[2048];
int length;
while ((length = fis.read(bytes)) >= 0) {
zous.write(bytes, 0, length);
}
zous.closeEntry();
}
}
baous.writeTo(fouscrx);
} catch (FileNotFoundException ex) {} catch (IOException ex) {}

第二个 示例没有像我希望的那样工作。我的意思是文件内容不是空的,而是'好像 zip 文件已损坏。

我希望你能告诉我为什么第一个例子不起作用。

最佳答案

ZipOutputStream has to do several operations at the end of the stream完成 zip 文件,因此有必要正确关闭它。 (一般来说,几乎每个流都应该正确关闭,这也是一种很好的做法。)

关于java - 为什么在这种情况下我必须以某种方式关闭 ZipOutputStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28636416/

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