Search code examples
javazip4j

Replace specific file inside Zip archive without extracting the whole archive in Java


I'm trying to get a specific file inside a Zip Archive, extract it, Encrypt it, and then get it back inside the archive replacing the origial one.

here's what I've tried so far..

public static boolean encryptXML(File ZipArchive, String key) throws ZipException, IOException, Exception {
    ZipFile zipFile = new ZipFile(ZipArchive);
    List<FileHeader> fileHeaderList = zipFile.getFileHeaders();
    for (FileHeader fh : fileHeaderList)
    {
        if (fh.getFileName().equals("META-INF/file.xml"))
        {
            Path tempdir = Files.createTempDirectory("Temp");
            zipFile.extractFile(fh, tempdir.toString());
            File XMLFile = new File(tempdir.toFile(), fh.getFileName());

            // Encrypting XMLFile, Ignore this part

            // Here, Replace the original XMLFile inside ZipArchive with the encrypted one <<<<<<<<

            return true;
        }
    }
    return false;
}

I stuck at the replacing part of the code is there anyway I can do this without having to extract the whole Zip Archive?

Any help is appreciated, thanks in advance.


Solution

  • Bingo!

    I'm able to do it that way

    ZipParameters parameters = new ZipParameters();
    parameters.setIncludeRootFolder(true);
    zipFile.removeFile(fh);
    zipFile.addFolder(new File(tempdir.toFile(), "META-INF"), parameters);