Java - 附加新 ZipEntry 时删除 ZipEntries

Java - ZipEntries being removed when appending new ZipEntry

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

出于某种原因,我无法解释此过程从 ZipFile 中删除了所有其他 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 的 class 文件复制到一个 zip 文件中。但是在这样做时它的所有其他内容都会被删除。

您没有读取 Zip 文件,您只是在文件级别覆盖它。

使用 NIO.2 文件 API 将文件复制到 zip 文件变得更加容易。

尝试(未测试):

try (FileSystem zipFS =  FileSystems.newFileSystem(URI.create("jar:" + zipURI), Collections.<String, Object>emptyMap())) {  
    Path targetInZipPath = zipFS.getPath(targetInZipPathString);  

    Files.copy(srcPath, targetInZipPath);  
}