public static void replaceInZip ( File zip , String file , String data , String encoding ) throws IOException { // open the output side File zipOutFile = File . createTempFile ( "ZipReplace" , ".zip" ) ; try { FileOutputStream fos = new FileOutputStream ( zipOutFile ) ; try ( ZipOutputStream zos = new ZipOutputStream ( fos ) ) { // open the input side try ( ZipFile zipFile = new ZipFile ( zip ) ) { boolean found = false ; // walk all entries and copy them into the new file Enumeration < ? extends ZipEntry > entries = zipFile . entries ( ) ; while ( entries . hasMoreElements ( ) ) { ZipEntry entry = entries . nextElement ( ) ; try { if ( entry . getName ( ) . equals ( file ) ) { zos . putNextEntry ( new ZipEntry ( entry . getName ( ) ) ) ; IOUtils . write ( data , zos , encoding ) ; found = true ; } else { zos . putNextEntry ( entry ) ; IOUtils . copy ( zipFile . getInputStream ( entry ) , zos ) ; } } finally { zos . closeEntry ( ) ; } } if ( ! found ) { zos . putNextEntry ( new ZipEntry ( file ) ) ; try { IOUtils . write ( data , zos , "UTF-8" ) ; } finally { zos . closeEntry ( ) ; } } } } // copy over the data FileUtils . copyFile ( zipOutFile , zip ) ; } finally { if ( ! zipOutFile . delete ( ) ) { //noinspection ThrowFromFinallyBlock throw new IOException ( "Error deleting file: " + zipOutFile ) ; } } }
Replaces the specified file in the provided ZIP file with the provided content .