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

孤人 提交于 2019-12-29 06:29:47

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/32353423/can-a-jar-file-be-updated-programmatically-without-rewriting-the-whole-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!