John Farrelly
John Farrelly

Reputation: 7459

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.

Upvotes: 6

Views: 4934

Answers (2)

John Farrelly
John Farrelly

Reputation: 7459

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 ); 
        } 
    }
}

Upvotes: 6

Marufur Rahman
Marufur Rahman

Reputation: 89

Yes, if you use this opensource library you can modify it in this way as well.

https://truevfs.java.net

public static void main(String args[]) throws IOException{
    File entry = new TFile("c:/tru6413/server/lib/nxps.jar/dir/second.txt");
    Writer writer = new TFileWriter(entry);
    try {
        writer.write(" this is writing into a file inside an archive");         
    } finally {
        writer.close();
    }       
}

Upvotes: 1

Related Questions