JAR file

How can I programatically extract a file from a JAR? My need is to parse a file that is part of a JAR...so I need to somehow obtain that file from the JAR, parse it, perhaps modify it, and then put it back into the jar.

Jar files are really just zip files, with the addition of the manifest. You can use either the java.util.zip or the java.util.jar package to handle them (you need to use the jar package only if you need manifest-specific functionality).

Shitij Agarwal

Greenhorn

Posts: 21

posted 12 years ago

Thanks. Once I obtain the entries of the zip/jar file, how can i open a specific file? Do I need to store that file somewhere on disk and then use java's i/o library to read it...or os it saved in memory?

Ulf Dittmer

Rancher

Posts: 42975

76

posted 12 years ago

No, you can read it directly w/o storing it someplace in between. Use the java.util.zip.ZipFile.getInputStream(ZipEntry entry) method, which returns a stream from which to read the file contents.

Shitij Agarwal

Greenhorn

Posts: 21

posted 12 years ago

I actually already have a method that takes in the name of a file to parse. Parsing in that method is done using BufferedReader's readLine() method.

So, I'm not sure how the InputStream can be used here...once I get the input stream, is it possible to read the file one line at a time just how it can be done using BufferedReader?

Have a look at the javadocs of the java.util.zip and java.util.jar packages. If you have a JarFile/ZipFile, what can you do with it? [ January 23, 2006: Message edited by: Ulf Dittmer ]

Shitij Agarwal

Greenhorn

Posts: 21

posted 12 years ago

Well, from the API it doesn't seem like I can delete a file from a jar. The only way it seems I could do this is to create a new jar and copy all the files from the original jar except the file I wish to delete.

Is that true?

Thanks.

Shitij Agarwal

Greenhorn

Posts: 21

posted 12 years ago

Do any of you know of an API that allows you to make a change to a file within a JAR in-place?

The java.util.zip and java.util.jar packages don't allow me to do this. The approach I need to use is to create a new jar file and copy the contents of the original jar and the edited file. For some reason, this approach is not convinient in my application...and I'd rather like to just edit the file in the existing jar itself. Any ideas?