Java 更新zip存档中的文件

Java 更新zip存档中的文件,java,zip,Java,Zip,我想更新zip存档中的文件,而不需要创建新的存档。我知道这可以通过创建一个新的归档文件、处理所有其他文件并在中添加更改的文件来实现 下面是演示该问题的代码。第一部分创建初始zip存档,其中包含一个文件,内容为helloworld。第二部分应该用Bye,Bye。最后一节再次解压zip,以便可以预期内容: try { // Create the initial zip archive with the original file content File file1 = new Fi

我想更新zip存档中的文件,而不需要创建新的存档。我知道这可以通过创建一个新的归档文件、处理所有其他文件并在中添加更改的文件来实现

下面是演示该问题的代码。第一部分创建初始zip存档,其中包含一个文件,内容为
helloworld。第二部分应该用
Bye,Bye。最后一节再次解压zip,以便可以预期内容:

try {
    // Create the initial zip archive with the original file content
    File file1 = new File(ReplaceFileInZipDemo.class.getResource("/helloworld.txt").toURI());
    File zipFile = new File("output.zip");
    FileOutputStream fos = new FileOutputStream(zipFile);
    ZipOutputStream zipOut = new ZipOutputStream(fos);
    FileInputStream fis = new FileInputStream(file1);
    ZipEntry zipEntry = new ZipEntry(file1.getName());
    zipOut.putNextEntry(zipEntry);
    byte[] bytes = new byte[1024];
    int length;
    while ((length = fis.read(bytes)) >= 0) {
        zipOut.write(bytes, 0, length);
    }
    fis.close();
    zipOut.close();
    fos.close();

    // Replace the original file content with a different file content, updating the file.
    File file2 = new File(ReplaceFileInZipDemo.class.getResource("/goodbyeworld.txt").toURI());
    Path zipfile = zipFile.toPath();
    FileSystem fs = FileSystems.newFileSystem(zipfile, null);
    Path pathInZipfile = fs.getPath(file1.getName());
    Files.copy(file2.toPath() , pathInZipfile, StandardCopyOption.REPLACE_EXISTING );

    // Extract the content of the updated file
    String destinationDir = System.getProperty("java.io.tmpdir");
    File targetDir = new File(destinationDir);
    ZipInputStream i = new ZipInputStream(new FileInputStream(zipFile));
    ZipEntry entry = null;
    System.out.println("Original file content:");
    Files.readAllLines(file1.toPath(), StandardCharsets.UTF_8).forEach(line -> System.out.println(line));
    System.out.println("Expected replaced file content");
    Files.readAllLines(file2.toPath(), StandardCharsets.UTF_8).forEach(line -> System.out.println(line));
    while ((entry = i.getNextEntry()) != null) {
        File destFile = new File(targetDir, entry.getName());
        String name = destFile.getAbsolutePath();
        File f = new File(name);
        try (OutputStream o = Files.newOutputStream(f.toPath())) {
            IOUtils.copy(i, o);
        }
        System.out.println("Content of extracted file " + name);
        Files.readAllLines(f.toPath(), StandardCharsets.UTF_8).forEach(line -> System.out.println(line));

    }
} catch (Exception e) {
    e.printStackTrace();
}
我得到的结果是:

Original file content:
Hello world!
Expected replaced file content
Bye, bye!
Content of extracted file /tmp/helloworld.txt
Hello world!
我能想象这不能像预期的那样工作的唯一原因是,替换内容来自一个与归档文件中名称不同的文件。但是当添加
文件时,删除(pathInZipfile)
要完全删除原始文件,它仍然存在

如何用另一个文件的内容替换存档中的文件内容