1
這是我如何創建3個文件的Java創建嵌套壓縮遞歸內存
FileOutputStream fos = new FileOutputStream(new File("out.zip"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
for (int i = 0; i < 3; i++) {
String s = "hello world " + i;
ZipEntry entry = new ZipEntry("text" + i + ".txt");
zos.putNextEntry(entry);
zos.write(s.getBytes());
zos.closeEntry();
}
}
baos.writeTo(fos);
我怎樣才能把拉鍊內袋遞歸在一個回合中對飛一個簡單的zip壓縮包?有什麼方法可以將ZipOutputStream
或ZipEntry
放在彼此之內嗎?
編輯:
解決方案馬克建議:
FileOutputStream fos = new FileOutputStream(new File("out.zip"));
ByteArrayOutputStream resultBytes = new ByteArrayOutputStream();
ByteArrayOutputStream zipOutStream = new ByteArrayOutputStream();
try (ZipOutputStream zos2 = new ZipOutputStream(zipOutStream)) {
String s = "hello world ";
ZipEntry entry = new ZipEntry("text.txt");
zos2.putNextEntry(entry);
zos2.write(s.getBytes());
zos2.closeEntry();
zos2.close();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
ZipEntry entry = new ZipEntry("text.zip");
zos.putNextEntry(entry);
zos.write(zipOutStream.toByteArray());
zos.closeEntry();
}
baos.writeTo(resultBytes);
resultBytes.writeTo(fos);
哦,這很容易。謝謝馬克。我只需要將第一個ByteArrayOutputStream字節傳遞給下面的ZipOutputStream.write()方法。 –