我有两个例子:
示例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) {}
第二个示例无法按我希望的方式工作。我的意思是,文件内容不是空的,但它s就好像zip文件已损坏一样。
我希望你告诉我为什么第一个例子不起作用
ZipOutputStream
必须在流的末尾执行多个操作才能完成zip文件,因此必须正确关闭它。(一般来说,几乎每个流都应该正确地关闭,这也是一种良好的做法。)
好吧,看起来try with resources自动关闭顺序很重要,并且在展开东西时必须首先关闭ZipOutputStream。在这种情况下,自动关闭的发生顺序与创建顺序相反。
如果重新排序第二个示例,使ZipOutputStream位于FileOutputStream之后,会发生什么?(尽管如果你问我的话,把ZipOutputStream放在它自己的try-catch块中是更清晰的代码。我们将相关和不相关的流分开,并以易于阅读的方式处理自动关闭。)
更新
FWIW,这是我过去在将zip流式传输到缓冲输出流时使用的习惯用法:
try (final ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(
new FileOutputStream(zipFile.toString())))) { ... }