【问题标题】:Is there any way to create zip in a zip file using java dynamically..?有没有办法使用java动态地在zip文件中创建zip..?
【发布时间】:2014-10-11 03:00:55
【问题描述】:

我有一堆文件,比如 4 个文件。我想将 2 个文件压缩成一个 zip,比如“inner.zip” 其余到“outer.zip”的父目录。

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);
                }

【问题讨论】:

  • 为什么要在 zip 中制作 zip?为什么不只是一个文件夹?

标签: java dynamic zip compression archive


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-04-28
    • 2013-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多