我有两个例子:
示例 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 文件已损坏。
我想让你告诉我为什么第一个例子不起作用。