Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jar

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.

like image 837
John Farrelly Avatar asked Sep 02 '15 12:09

John Farrelly


Video Answer


1 Answers

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

import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;

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 ); 
        } 
    }
}
like image 54
John Farrelly Avatar answered Sep 21 '22 10:09

John Farrelly