Getting a specific file from ZipInputStream

I can go through ZipInputStream , but before starting the iteration I want to get the specific file that I need during the iteration. How can i do this?

 ZipInputStream zin = new ZipInputStream(myInputStream) while ((entry = zin.getNextEntry()) != null) { println entry.getName() } 
+5
source share
3 answers

If the myInputStream you are working with comes from a real file on disk, you can simply use java.util.zip.ZipFile instead, which is supported by RandomAccessFile and provides direct access to zip records by name. But if all you have is an InputStream (for example, if you process the stream directly when receiving from a network socket or similar), you will need to do your own buffering.

You can copy the stream to a temporary file, then open this file with a ZipFile or, if you ZipFile know the maximum data size (for example, for an HTTP request declaring its Content-Length in front), you can use BufferedInputStream to buffer it in memory until until you find the record you want.

 BufferedInputStream bufIn = new BufferedInputStream(myInputStream); bufIn.mark(contentLength); ZipInputStream zipIn = new ZipInputStream(bufIn); boolean foundSpecial = false; while ((entry = zin.getNextEntry()) != null) { if("special.txt".equals(entry.getName())) { // do whatever you need with the special entry foundSpecial = true; break; } } if(foundSpecial) { // rewind bufIn.reset(); zipIn = new ZipInputStream(bufIn); // .... } 

(I have not tested this code myself, you can find something like commons-io CloseShieldInputStream between bufIn and the first zipIn to allow closing the first zip stream without closing the underlying bufIn before rewinding it).

+2
source

use the getName () method in ZipEntry to get the file you want.

 ZipInputStream zin = new ZipInputStream(myInputStream) String myFile = "foo.txt"; while ((entry = zin.getNextEntry()) != null) { if (entry.getName().equals(myFileName)) { // process your file // stop looking for your file - you've already found it break; } } 

Starting with Java 7, you better use a ZipFile instead of a ZipStream if you only need one file and you have a file to read from:

 ZipFile zfile = new ZipFile(aFile); String myFile = "foo.txt"; ZipEntry entry = zfile.getEntry(myFile); if (entry) { // process your file } 
+3
source

See Searching a File in a Zip Record

 ZipFile file = new ZipFile("file.zip"); ZipInputStream zis = searchImage("foo.png", file); public searchImage(String name, ZipFile file) { for (ZipEntry e : file.entries){ if (e.getName().endsWith(name)){ return file.getInputStream(e); } } return null; } 
+1
source

All Articles