有没有办法在Java中动态创建zip文件中的zip文件?

3
我有一堆文件,比如说4个文件...我想要将其中2个文件压缩成一个名为“inner.zip”的压缩包,而其他文件则压缩到“outer.zip”所在的父级目录。
即: enter image description here
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);
                }

1
为什么要在zip文件中再创建一个zip文件?为什么不直接使用文件夹呢? - Arvy
1个回答

4
内部的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().

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接