John Farrelly John Farrelly - 1 year ago 75
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

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
, so I was wondering if there was a similar "random access" way to do this. Given that it can be done using the
tool, I had expected there to be a similar way to do it programmatically.

Answer Source

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.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
        URI uri = URI.create("jar:file:/codeSamples/zipfs/");

       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 ); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download