John Farrelly John Farrelly - 2 months ago 17
Java Question

Can a Jar File be updated programmatically without rewriting the whole file?

It is possible to update individual files in a JAR file using the

jar
command as follows:

jar uf TicTacToe.jar images/new.gif


Is there a way to do this programmatically?

I have to rewrite the entire jar file if I use
JarOutputStream
, so I was wondering if there was a similar "random access" way to do this. Given that it can be done using the
jar
tool, I had expected there to be a similar way to do it programmatically.

Answer

It is possible to update just parts of the JAR file using Zip File System Provider available in Java 7:

import java.util.*;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.*;

public class ZipFSPUser {
    public static void main(String [] args) throws Throwable {
        Map<String, String> env = new HashMap<>(); 
        env.put("create", "true");
        // locate file system by using the syntax 
        // defined in java.net.JarURLConnection
        URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");

       try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
            Path externalTxtFile = Paths.get("/codeSamples/zipfs/SomeTextFile.txt");
            Path pathInZipfile = zipfs.getPath("/SomeTextFile.txt");          
            // copy a file into the zip file
            Files.copy( externalTxtFile,pathInZipfile, 
                    StandardCopyOption.REPLACE_EXISTING ); 
        } 
    }
}