Java - 附加新的 ZipEntry 时 ZipEntries 被删除

标签 java zip file-copying

我正在尝试创建一种将 java.io.File 复制到 java.util.zip.ZipFile 的方法。为此,我首先打开 ZipFile 的 java.util.zip.ZipOutputStream,然后使用文件名创建一个新的 java.util.zip.ZipEntry,将新的 ZipEntry 放入 ZipOutputStream 中,然后写入文件的内容到 ZipOutputStream。之后,我刷新 ZipOutputStream 并关闭所有流。

出于某种原因,我无法解释此过程会从 ZipFile 中删除所有其他 ZipEntries,并且只将复制的 ZipEntries 保留在其中。下面是复制文件的代码(文件由java.io.InputStream参数表示)

    public static boolean compress(final InputStream pSourceStream, final ZipFile pTarget, final ZipEntry pContainer,
        final String pFileName) {
    if (pSourceStream != null && pTarget != null && pFileName != null && !pFileName.isEmpty()) {
        try {
            final ZipOutputStream output = new ZipOutputStream(new FileOutputStream(new File(pTarget.getName())));
            final ZipEntry target = (pContainer != null) ? new ZipEntry(pContainer.getName() + pFileName)
                    : new ZipEntry(pFileName);
            output.putNextEntry(target);

            final byte[] buffer = new byte[BUFFER_SIZE];
            int readBytes;

            while ((readBytes = pSourceStream.read(buffer)) != -1) {
                output.write(buffer, 0, readBytes);
            }
            pSourceStream.close();
            output.flush();
            output.close();
            return true;
        } catch (final IOException ignore) {
            // took care of target
            // ios will return false
        }

    }
    return false;
}

这是我调用此方法的代码

public static void main(final String[] args) throws ZipException, IOException {
    final Package p = FileHandler.class.getPackage();
    final InputStream classStream = FileHandler.stream(p, "FileHandler.class");

    FileHandler.compress(classStream, new ZipFile(new File("C:/Users/litts/Desktop/FileHandlerTest/TestZip.jar")),
            "FileHandler1.class");

}

所以我在这里基本上做的是将 FileHandler 的类文件复制到 zip 文件。但这样做时,其所有其他内容都会被删除。

最佳答案

您不是在读取 Zip 文件,而是在文件级别覆盖它。

关于Java - 附加新的 ZipEntry 时 ZipEntries 被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37160705/

相关文章:

java - hibernate不断更新第一条记录的值而不是创建新记录

java - JAVA生成唯一随机数

java - java中等待一个C++编写的多线程程序

c++ - 免费的基于 C/C++ 的 zip/zip64 库?

c# - 将 CopyFileEx 转换为任务模式

c# - "Could not find part of the path"复制文件时出错

c# - C# 中的高性能文件复制?

从另一个类访问 Java Swing/AWT 组件

python - 从 zip 文件中的 csv 创建 Dataframe

c# - 使用 Shims 对 ZipFile 进行单元测试