Read a zip file inside zip file

后端 未结 4 1407
长情又很酷
长情又很酷 2020-12-11 16:14

I have zip file which is inside a folder in zip file please suggest me how to read it using zip input stream.

E.G.:

abc.zip
    |
      documents/b         


        
4条回答
  •  执笔经年
    2020-12-11 17:04

    The following code snippet lists the entries of a ZIP file inside another ZIP file. Adapt it to your needs. ZipFile uses ZipInputStreams underneath the hood.

    The code snippet uses Apache Commons IO, specifically IOUtils.copy.

    public static void readInnerZipFile(File zipFile, String innerZipFileEntryName) {
        ZipFile outerZipFile = null;
        File tempFile = null;
        FileOutputStream tempOut = null;
        ZipFile innerZipFile = null;
        try {
            outerZipFile = new ZipFile(zipFile);
            tempFile = File.createTempFile("tempFile", "zip");
            tempOut = new FileOutputStream(tempFile);
            IOUtils.copy( //
                    outerZipFile.getInputStream(new ZipEntry(innerZipFileEntryName)), //
                    tempOut);
            innerZipFile = new ZipFile(tempFile);
            Enumeration entries = innerZipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                System.out.println(entry);
                // InputStream entryIn = innerZipFile.getInputStream(entry);
            }
    
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // Make sure to clean up your I/O streams
            try {
                if (outerZipFile != null)
                    outerZipFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            IOUtils.closeQuietly(tempOut);
            if (tempFile != null && !tempFile.delete()) {
                System.out.println("Could not delete " + tempFile);
            }
            try {
                if (innerZipFile != null)
                    innerZipFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args) {
        readInnerZipFile(new File("abc.zip"), "documents/bcd.zip");
    }
    

提交回复
热议问题