为什么在这种情况下必须以某种方式关闭ZipOutputStream?
我有两个例子:
范例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
必须在流的末尾执行多项操作以完成zip文件,因此必须正确关闭它。(一般来讲,按照惯例,每个流几乎都
应该 正确关闭。)
以上是 为什么在这种情况下必须以某种方式关闭ZipOutputStream? 的全部内容, 来源链接: utcz.com/qa/414185.html