Search code examples
javafilezipinputstream

Replacing a Zip file without unzipping in Java


I have a zip file and I want to replace one file inside it with another file. So do not need to delete a zip entry just replace the file for the zip entry with another.

Here is what I have tried.

public void replaceConfigurationFile(ZipFile zipFile, ZipOutputStream zos, String pathToNewFile, String configFileToReplaced) 
        throws IOException {
    String zipEntryName;
    for(Enumeration<?> e = zipFile.entries(); e.hasMoreElements(); ) {

        ZipEntry entryIn = (ZipEntry) e.nextElement();
        zipEntryName = entryIn.getName();
            if(zipEntryName.endsWith(configFileToReplaced)) {

                FileInputStream fis = new FileInputStream(pathToNewFile);
                ZipEntry zipEntry = new ZipEntry(zipEntryName);

                zos.putNextEntry(zipEntry);

                byte[] bytes = new byte[1024];
                int length;
                while ((length = fis.read(bytes)) >= 0) {
                    zos.write(bytes, 0, length);
                }

                zos.closeEntry();
                fis.close();
            } else {
                zos.putNextEntry(entryIn);
                InputStream is = zipFile.getInputStream(entryIn);
                byte [] buf = new byte[1024];
                int len;
                while((len = (is.read(buf))) > 0) {            
                    zos.write(buf, 0, len);
                }
             zos.closeEntry();  
           }


    } // enf of for
}   

I have a file zip Entry named :

WEB-INF/classes/config/app-dev.yml

and I have a file at location d drive at location

 D:/app-dev.yml

I am able to copy the file in to a different zip file by replacing the file i want to replace . But that is really not needed (to create a different file). So what should I do to just replace the file with my custom file.

I have searched different posts in Stackoverflow, but unable to find what i need. I read that zip entry cannot be deleted but what about replacing it ? Please help


Solution

  • Your problem is that the new file might be larger than the old file - or smaller! You need to do exactly what you did to allow for the change. The probability that the new file, ZIPped, is exactly the same size as the previous one is virtually nil.