我有一堆文件,说4个文件..我想将2个文件压缩成拉链说“inner.zip” 其余的到“outer.zip”的父目录。
I.e
InputStream streamToReadFile=readFile(filePath);
String zipEntryName = folderName + "/" + fileNameToWrite;
ZipEntry anEntry = new ZipEntry(zipEntryName);
// I couldn't able to create zip in a zip file.
streamToWriteInZip.putNextEntry(anEntry);
while ((bytesIn = streamToReadFile.read(readBuffer)) > 0) {
streamToWriteInZip.write(readBuffer, 0, bytesIn);
}
答案 0 :(得分:2)
内部ZipOutputStream应该调用finish()
而不是close()
,因为finish()
会刷新所有压缩数据,但不会关闭外部zip。 介意测试close()
的错误,需要添加另一个文件,因为内部zip是最后一个。
Path sourcePath = Paths.get("C:/D/test.html");
try (ZipOutputStream zipOut = new ZipOutputStream(
new FileOutputStream("C:/D/test/test.zip"))) {
zipOut.putNextEntry(new ZipEntry("file1.txt"));
Files.copy(sourcePath, zipOut);
zipOut.closeEntry();
zipOut.putNextEntry(new ZipEntry("file2.txt"));
Files.copy(sourcePath, zipOut);
zipOut.closeEntry();
zipOut.putNextEntry(new ZipEntry("inner.zip"));
ZipOutputStream innerZipOut = new ZipOutputStream(zipOut);
{
innerZipOut.putNextEntry(new ZipEntry("file3.txt"));
Files.copy(sourcePath, innerZipOut);
innerZipOut.closeEntry();
innerZipOut.putNextEntry(new ZipEntry("file4.txt"));
Files.copy(sourcePath, innerZipOut);
innerZipOut.closeEntry();
innerZipOut.finish(); // Instead of close().
}
zipOut.closeEntry();
} catch (IOException e) {
e.printStackTrace();
} // Invoke close().