简体   繁体   中英

How to read all files from a zip file

I'd like to recursively read a zip file and then extract all files in a separate folder.

For example if some.zip file has the following contents:

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

What I want is just all the files, including all the files in zip files inside the zip file ( inside.zip in the example above).

end result of somefolder would be all the files (I don't care about the folder structure):

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

What I tried:

I have the code below but it maintains the folder structure and does not open zip files inside 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 as File).with{ f ->
            f.parentFile?.mkdirs()
            f.withOutputStream { w ->
                w << zip.getInputStream(e)
            }
        }
    }
}
  • Iterate through the entries
  • If the file is not a .zip file then extract it
  • If the file is a zip file then get the inputStream for its entry. Create a new ZipInputStream. Extract the 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")); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM