tags:

views:

495

answers:

3

I've got a WAR file that I need to add two files to. Currently, I'm doing this:

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

The result is that the previous contents get clobbered: the WAR has only the 2 files I just added in it. Is there some sort of append mode that I'm not using or what?

+4  A: 

Yeah, there's an extra boolean argument to the FileOutputStream constructor which lets you force it to append to the file rather than overwrite it. Change your code to

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

and it should work the way you want.

hark
+1  A: 

It seems this can't be done. I thought it was for a while, but it seems that it wasn't quite having the effect I wanted. Doing it this way resulted in the equivalent of two separate jar files concatinated together. The weird part was that the tools were making some sense of it. JAR found the first, original jar file and read me that. Glassfish's classloader was finding the later, new part, resulting in it loading only the added files as if they were all of the app. Weird.

So I've resurted to creating a new war, adding the contents of the old, adding the new files, closing, and copying the new over the old.

sblundy
A: 

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.

Steve K