【发布时间】:2020-06-21 13:55:40
【问题描述】:
我想将以前从其他文件(已经完成)提取的一系列文件添加到 jar 中。这些文件将覆盖 JAR 中的文件。最有效的方法是什么? 我需要它快。 谢谢!
【问题讨论】:
我想将以前从其他文件(已经完成)提取的一系列文件添加到 jar 中。这些文件将覆盖 JAR 中的文件。最有效的方法是什么? 我需要它快。 谢谢!
【问题讨论】:
jar -u file.jar file1 file2 file3 ...
【讨论】:
jar -uf my.jar file1 file2...
jar -uf my.jar dir/
或混合
jar -uf my.jar file dir/
【讨论】:
jar -u 时,我不得不按 Ctrl + C 以使脚本继续(出于某种莫名其妙的原因)。添加-f 修复它。
JAR 文件是 ZIP 文件,请记住。
只需使用一些 ZIP 库。
【讨论】:
只是为了补充现有答案,至少有一种特殊情况:所谓的可执行 JAR 文件。如果你添加另一个 JAR 文件作为依赖项——无论你使用 jar 还是 zip——它都会抱怨嵌入的文件被压缩:
Caused by: java.lang.IllegalStateException: Unable to open nested entry 'BOOT-INF/lib/file.jar'. It has been compressed and nested jar files must be stored without compression. Please check the mechanism used to create your executable jar file
对此的解决方案是使用0 选项来jar:
jar uvf0 myfile.jar BOOT-INF/lib/file.jar
普通的类文件不需要这个。
【讨论】:
zip file.jar file1 file2 file3
适用于 Mac Os 10.7.5
【讨论】:
//Add a file in jar in a particular folder
jar uvf <jar file name> <file to be added> <folder name inside jar>
【讨论】:
<folder name inside jar> 使用什么。我的用例是src/config.properties。我试过jar --update --file=../demo.jar --main-class=demo.App src/config.properties <???>。
扩展现有答案,我发现 -C jar 选项在添加位于自己文件夹中的文件并且您将其路径展平时非常有用。
$ jar uf jar-file -C /path/to/my_jars/ this_useful.jar
您最终会在 JAR 的根目录中拥有 this_useful.jar:
$ jar tf jar-file | grep this_useful.jar
this_useful.jar
【讨论】:
如果有人需要以编程方式回答,这里就是。
private static void createJar(File source, JarOutputStream target) {
createJar(source, source, target);
}
private static void createJar(File source, File baseDir, JarOutputStream target) {
BufferedInputStream in = null;
try {
if (!source.exists()) {
throw new IOException("Source directory is empty");
}
if (source.isDirectory()) {
// For Jar entries, all path separates should be '/'(OS independent)
String name = source.getPath().replace("\\", "/");
if (!name.isEmpty()) {
if (!name.endsWith("/")) {
name += "/";
}
JarEntry entry = new JarEntry(name);
entry.setTime(source.lastModified());
target.putNextEntry(entry);
target.closeEntry();
}
for (File nestedFile: source.listFiles()) {
createJar(nestedFile, baseDir, target);
}
return;
}
String entryName = baseDir.toPath().relativize(source.toPath()).toFile().getPath().replace("\\", "/");
JarEntry entry = new JarEntry(entryName);
entry.setTime(source.lastModified());
target.putNextEntry(entry); in = new BufferedInputStream(new FileInputStream(source));
byte[] buffer = new byte[1024];
while (true) {
int count = in .read(buffer);
if (count == -1)
break;
target.write(buffer, 0, count);
}
target.closeEntry();
} catch (Exception ignored) {
} finally {
if ( in != null) {
try { in .close();
} catch (Exception ignored) {
throw new RuntimeException(ignored);
}
}
}
}
【讨论】:
String cmd = "jar uvf " + "jarName" + " " + "Filename";
System.out.println(cmd);
try {
Process p = Runtime.getRuntime().exec(cmd);
}
catch (Exception ex) {
}
【讨论】: