0

我有一个需要添加两个文件的 WAR 文件。目前,我正在这样做:

File war = new File(DIRECTORY, "server.war");
JarOutputStream zos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(war)));

//Add file 1
File file = new File(DIRECTORY, "file1.jar");
InputStream is = new BufferedInputStream(new FileInputStream(file));
ZipEntry e = new ZipEntry("file1.jar");
zos.putNextEntry(e);
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf, 0, buf.length)) != -1) {
    zos.write(buf, 0, len);
}
is.close();
zos.closeEntry();

//repeat for file 2

zos.close();

结果是先前的内容被破坏了:WAR 中只有我刚刚添加的 2 个文件。是否有某种我没有使用的附加模式或什么?

4

3 回答 3

6

是的, FileOutputStream 构造函数有一个额外的布尔参数,可让您强制它附加到文件而不是覆盖它。将您的代码更改为

JarOutputStream zos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(war, True)));

它应该按照你想要的方式工作。

于 2008-11-05T20:12:56.983 回答
2

这似乎是做不到的。我以为是有一段时间了,但似乎并没有达到我想要的效果。这样做相当于将两个单独的 jar 文件连接在一起。奇怪的是,这些工具能理解它。JAR 找到了第一个原始的 jar 文件并读给我看。Glassfish 的类加载器正在寻找后来的新部分,导致它只加载添加的文件,就好像它们是整个应用程序一样。奇怪的。

所以我决定创建一个新的战争,添加旧的内容,添加新的文件,关闭,并在旧的上复制新的。

于 2008-11-06T18:34:09.833 回答
0

I have the same problem; I'm looking for an easy way to update a file in an existing jar file. If it's so easy to do a "jar uf foo.jar ..." command, how come there isn't a way to use Java API's to do the same?

Anyway, here is the RFE to add this functionality to Java; it also suggests some work-arounds:

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4129445

And here is a library that purports to make this a lot easier, by treating JARs/ZIPs like virtual directories:

https:// truezip.dev.java.net

I haven't figured out yet which approach I'm going to use for my current problem.

于 2010-07-20T23:11:05.477 回答