How to unzip files recursively in Java?

后端 未结 9 2006
慢半拍i
慢半拍i 2020-11-27 03:10

I have zip file which contains some other zip files.

For example, the mail file is abc.zip and it contains xyz.zip, class1.java

相关标签:
9条回答
  • 2020-11-27 03:39

    Modified as i needed then mixed in a bit of the best answers. This version will:

    • Recursively Extract a zip to given location

    • Create empty directories

    • Close zip properly


    public static void unZipAll(File source, File destination) throws IOException 
    {
        System.out.println("Unzipping - " + source.getName());
        int BUFFER = 2048;
    
        ZipFile zip = new ZipFile(source);
        try{
            destination.getParentFile().mkdirs();
            Enumeration zipFileEntries = zip.entries();
    
            // Process each entry
            while (zipFileEntries.hasMoreElements())
            {
                // grab a zip file entry
                ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
                String currentEntry = entry.getName();
                File destFile = new File(destination, currentEntry);
                //destFile = new File(newPath, destFile.getName());
                File destinationParent = destFile.getParentFile();
    
                // create the parent directory structure if needed
                destinationParent.mkdirs();
    
                if (!entry.isDirectory())
                {
                    BufferedInputStream is = null;
                    FileOutputStream fos = null;
                    BufferedOutputStream dest = null;
                    try{
                        is = new BufferedInputStream(zip.getInputStream(entry));
                        int currentByte;
                        // establish buffer for writing file
                        byte data[] = new byte[BUFFER];
    
                        // write the current file to disk
                        fos = new FileOutputStream(destFile);
                        dest = new BufferedOutputStream(fos, BUFFER);
    
                        // read and write until last byte is encountered
                        while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                            dest.write(data, 0, currentByte);
                        }
                    } catch (Exception e){
                        System.out.println("unable to extract entry:" + entry.getName());
                        throw e;
                    } finally{
                        if (dest != null){
                            dest.close();
                        }
                        if (fos != null){
                            fos.close();
                        }
                        if (is != null){
                            is.close();
                        }
                    }
                }else{
                    //Create directory
                    destFile.mkdirs();
                }
    
                if (currentEntry.endsWith(".zip"))
                {
                    // found a zip file, try to extract
                    unZipAll(destFile, destinationParent);
                    if(!destFile.delete()){
                        System.out.println("Could not delete zip");
                    }
                }
            }
        } catch(Exception e){
            e.printStackTrace();
            System.out.println("Failed to successfully unzip:" + source.getName());
        } finally {
            zip.close();
        }
        System.out.println("Done Unzipping:" + source.getName());
    }
    
    0 讨论(0)
  • 2020-11-27 03:45

    Here's some untested code base on some old code I had that unzipped files.

    public void doUnzip(String inputZip, String destinationDirectory)
            throws IOException {
        int BUFFER = 2048;
        List zipFiles = new ArrayList();
        File sourceZipFile = new File(inputZip);
        File unzipDestinationDirectory = new File(destinationDirectory);
        unzipDestinationDirectory.mkdir();
    
        ZipFile zipFile;
        // Open Zip file for reading
        zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
    
        // Create an enumeration of the entries in the zip file
        Enumeration zipFileEntries = zipFile.entries();
    
        // Process each entry
        while (zipFileEntries.hasMoreElements()) {
            // grab a zip file entry
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
    
            String currentEntry = entry.getName();
    
            File destFile = new File(unzipDestinationDirectory, currentEntry);
            destFile = new File(unzipDestinationDirectory, destFile.getName());
    
            if (currentEntry.endsWith(".zip")) {
                zipFiles.add(destFile.getAbsolutePath());
            }
    
            // grab file's parent directory structure
            File destinationParent = destFile.getParentFile();
    
            // create the parent directory structure if needed
            destinationParent.mkdirs();
    
            try {
                // extract file if not a directory
                if (!entry.isDirectory()) {
                    BufferedInputStream is =
                            new BufferedInputStream(zipFile.getInputStream(entry));
                    int currentByte;
                    // establish buffer for writing file
                    byte data[] = new byte[BUFFER];
    
                    // write the current file to disk
                    FileOutputStream fos = new FileOutputStream(destFile);
                    BufferedOutputStream dest =
                            new BufferedOutputStream(fos, BUFFER);
    
                    // read and write until last byte is encountered
                    while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                        dest.write(data, 0, currentByte);
                    }
                    dest.flush();
                    dest.close();
                    is.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
        zipFile.close();
    
        for (Iterator iter = zipFiles.iterator(); iter.hasNext();) {
            String zipName = (String)iter.next();
            doUnzip(
                zipName,
                destinationDirectory +
                    File.separatorChar +
                    zipName.substring(0,zipName.lastIndexOf(".zip"))
            );
        }
    
    }
    
    0 讨论(0)
  • 2020-11-27 03:47

    One should CLOSE zip file after unzip.

    static public void extractFolder(String zipFile) throws ZipException, IOException 
    {
        System.out.println(zipFile);
        int BUFFER = 2048;
        File file = new File(zipFile);
    
        ZipFile zip = new ZipFile(file);
        try
        { 
           ...code from other answers ( ex. NeilMonday )...
        }
        finally
        {
            zip.close();
        }
    }
    
    0 讨论(0)
提交回复
热议问题