tags:

views:

818

answers:

2

I have a class which wraps ZipEntrys, but I'm struggling to see how I could then write a method that returns an input stream from any one ZipEntry. I managed to write something that could return an array of input streams for a ZipFile, but I need a way to get an input stream from just one ZipEntry.

+2  A: 

Do you not have the ZipFile instance from which the ZipEntry was sourced? If you do you could use ZipFile.getInputStream(ZipEntry).

http://java.sun.com/j2se/1.4.2/docs/api/java/util/zip/ZipFile.html

PS. Just had a quick look at the code and a ZipEntry is not a wrapper for the underlying data in the zip file. It is just a "place holder" for the entry as far as I can see (i.e. zipped file attributes not the data). The actual stream is created through a JNI call in the ZipFile class. Meaning that I do not believe you can do what you are looking to do in a practical way.

Malcolm Featonby
Malcolm, Thanks for the help, I just found that method. My problem now is that the code that originally 'opens' the zip file (when you do ZipFile zip = new ZipFile("path");), then closes it. I can stop it closing it if I want, but I was wondering - what are the consequences of not closing zips/jars? Obviously if I do remove the close() command I will leave a method so the user can close it later, but I was wondering what would happen if the user forgot - just greedy on memory?I know it isn't a wrapper for the data - what I'm writing is a wrapper for dealing with Zip/Jar files.
Stephen
Leaving it open doesn't feel like a good idea to me. Equally so for deferring responsibility for closing to the user of your solution. An option (possibly - I am guessing at the problem you are solving) is to wrap the ZipEntry and include with it a handle to the ZipFile in the wrapping class. This seems a little heavy but does mean that you can open\close a stream to the wrapped zip entry whenever you need.
Malcolm Featonby
+2  A: 

How about this?

ZipFile zipFile = new ZipFile("file.zip");
ZipEntry zipEntry = zipFile.getEntry("fileName.txt");    
InputStream inputStream zipFile.getInputStream(zipEntry)
OTisler
+1 for the code snippet.
Andy Gherna
Unfortunately creating a new instance of ZipFile leaks file handles in 1.4.2_12
nbolton