我有两个例子:
示例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文件已损坏。
我想告诉我第一个例子怎么行不通。
答案 0 :(得分:3)
ZipOutputStream
has to do several operations at the end of the stream完成zip文件,因此必须正确关闭它。 (一般来说,几乎每个流应该正确关闭,就像良好的做法一样。)
答案 1 :(得分:0)
好吧,看起来try-with-resources自动关闭顺序很重要,并且在解开东西时必须首先关闭ZipOutputStream。在这种情况下,自动关闭的发生方式与它们的创建方式相反。
如果重新排序第二个示例,ZipOutputStream位于FileOutputStream之后会发生什么? (虽然如果你问我,将ZipOutputStream放在它自己的try-catch块中是更清晰的代码。我们将相关和不相关的流分开并以易读的方式处理自动关闭。)
更新
FWIW,这是我过去在将zip压缩为缓冲输出流时使用的一种习惯用法:
try (final ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(
new FileOutputStream(zipFile.toString())))) { ... }