Thursday 15 September 2011

java - How to read all files from a zip file -



java - How to read all files from a zip file -

i'd recursively read zip file , extract files in separate folder.

for illustration if some.zip file has next contents:

file5.txt somefolder file.txt file4.txt inside.zip file2.txt file3.txt

what want files, including files in zip files within zip file (inside.zip in illustration above).

end result of somefolder files (i don't care folder structure):

file5.txt file.txt file4.txt file2.txt file3.txt

what tried:

i have code below maintains folder construction , not open zip files within zip files:

import java.util.zip.* def extractzip (string zipfile) { def zipin = new file(zipfile) def zip = new zipfile(zipin) zip.entries().findall { !it.directory }.each { e -> (e.name file).with{ f -> f.parentfile?.mkdirs() f.withoutputstream { w -> w << zip.getinputstream(e) } } } }

iterate through entries if file not .zip file extract it

if file zip file inputstream entry. create new zipinputstream. extract stream.

public void extract(zipinputstream zipfile, file outputdir) throws ioexception { zipentry entry; while ( ( entry = zipfile.getnextentry()) != null) { if (entry.isdirectory()) continue; if (entry.getname().endswith(".zip")) { extract(new zipinputstream(zipfile), outputdir); } else { extracttodir(zipfile, new file (outputdir, entry.getname())); } } } private void extracttodir(zipinputstream zipfile, file outfile) throws filenotfoundexception { bytestreams.copy(zipfile, new fileoutputstream(outfile)); } public static void main(string... args) { extract(new zipinputstream(new fileinputstream(zipfilename)), new file("outputpath")); }

java groovy zip

No comments:

Post a Comment