本文介绍了可以在不重写整个文件的情况下以编程方式更新 Jar 文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以使用 jar
命令更新 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?
如果我使用 JarOutputStream
,我必须重写整个 jar 文件,所以我想知道是否有类似的随机访问"方式来做到这一点.鉴于它可以使用 jar
工具完成,我原以为会有类似的方式以编程方式完成.
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.
推荐答案
可以使用 Zip 文件系统提供程序在 Java 7 中可用:
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 );
}
}
}
这篇关于可以在不重写整个文件的情况下以编程方式更新 Jar 文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!