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.
As far as I think, java.util.Zip allows you to treat a .jar file just like a .zip file. Thereof, you can use the following code snippet to parse through all the entries in that file :
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).
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?
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.
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?
Hello Shitij, JAR files are not merely a zip file with a manifest file. A JAR file is always a valid zip stream, but not necessarily the other way around.
Is it possible to delete a file from a JAR programatically?
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 ]
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.
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?