How should I extract compressed folders in java?

12,499

You can use File.mkdirs() to create folders. Try changing your method like this:

public static void getZipFiles(String filename) {
    try {
        String destinationname = "c:\\zip\\";
        byte[] buf = new byte[1024];
        ZipInputStream zipinputstream = null;
        ZipEntry zipentry;
        zipinputstream = new ZipInputStream(
                new FileInputStream(filename));

        zipentry = zipinputstream.getNextEntry();
        while (zipentry != null) {
            //for each entry to be extracted
            String entryName = destinationname + zipentry.getName();
            entryName = entryName.replace('/', File.separatorChar);
            entryName = entryName.replace('\\', File.separatorChar);
            System.out.println("entryname " + entryName);
            int n;
            FileOutputStream fileoutputstream;
            File newFile = new File(entryName);
            if (zipentry.isDirectory()) {
                if (!newFile.mkdirs()) {
                    break;
                }
                zipentry = zipinputstream.getNextEntry();
                continue;
            }

            fileoutputstream = new FileOutputStream(entryName);

            while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
                fileoutputstream.write(buf, 0, n);
            }

            fileoutputstream.close();
            zipinputstream.closeEntry();
            zipentry = zipinputstream.getNextEntry();

        }//while

        zipinputstream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Share:
12,499
Chathuranga Chandrasekara
Author by

Chathuranga Chandrasekara

A seasoned professional with 10+ years of Industry experience. The core competencies are, 1. Full Stack Solutions Architecture 2. Design and Implementation of Internet of Things (IoT) Software and Hardware/Firmware Programming Languages - Java | Python | NodeJS | JavaScript | TypeScript Front End Frameworks - Angular | React | Backbone | Bootstrap | Material Dependency Injection - Spring ORM - Hibernate Microservices - Spring Boot Batch Processing - Spring Batch Containerization - Docker Orchestration – Kubernetes Databases – MySQL | Postgres SQL | MS SQL Server NoSQL - MongoDB | Cassendra Build Tools – Maven | Gradle CI/CD – Jenkins | Ansible | Chef Testing - JUnit | Jasmine | Karma | RestAssured | Selenium Caching - Redis | Guava Dashboarding - Kibana | Banana Reporting - Jasper | Penthaho Health Monitoring – Prometheous | OpenTSDB | Ngios Messaging – RabbitMQ | Kafka API Gateways – Zuul | WSO2 API Manager | Nginx | Kong Cloud Services – AWS | OpenShift Identity Providers - KeyCloak | Apereo CAS REST Documentation - Swagger REST Security - JWT | OAuth2 Protocols - CoAP | STOMP | XMPP | TLS | REST | SOAP | MQTT | AMQP Source Management - Git | Subversion | Mercural Deep Learning & Numerical Calculation - Keras | Tensorflow | Caffe | Pandas | Numpy Image Processing and Computer Vision - OpenCV Project Management - Jira | ScrumWorks Programmable Hardware - Arduino | Rasberry Pi | PIC | ESP 32| ESP8266 GPRS & NB-IoT - SIM 800 | SIM 900 | SIM 7000 IoT Prototyping - NodeRed Search Engines - Elastic | Solr | Fast ESP Mobile – Android | Telerik NativeScript | Ionic 2 | React Native My other interests are, 1. Machine Learning 2. Deep Learning / Artificial Neural Networks 3. Artificial Intelligence

Updated on June 15, 2022

Comments

  • Chathuranga Chandrasekara
    Chathuranga Chandrasekara almost 2 years

    I am using the following code to extract a zip file in Java.

    import java.io.*;
    import java.util.zip.*;
    
    class  testZipFiles 
    {
        public static void main(String[] args) 
        {
    
            try
            {
                String filename = "C:\\zip\\includes.zip";
                testZipFiles list = new testZipFiles( );
                list.getZipFiles(filename);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    
        public void getZipFiles(String filename)
        {
            try
            {
                String destinationname = "c:\\zip\\";
                byte[] buf = new byte[1024];
                ZipInputStream zipinputstream = null;
                ZipEntry zipentry;
                zipinputstream = new ZipInputStream(
                new FileInputStream(filename));
    
                zipentry = zipinputstream.getNextEntry();
                while (zipentry != null) 
                { 
                    //for each entry to be extracted
                    String entryName = zipentry.getName();
                    System.out.println("entryname "+entryName);
                    int n;
                    FileOutputStream fileoutputstream;
                    File newFile = new File(entryName);
                    String directory = newFile.getParent();
    
                    if(directory == null)
                    {
                        if(newFile.isDirectory())
                        break;
                    }
    
                    fileoutputstream = new FileOutputStream(
                       destinationname+entryName);             
    
                    while ((n = zipinputstream.read(buf, 0, 1024)) > -1)
                        fileoutputstream.write(buf, 0, n);
    
                    fileoutputstream.close(); 
                    zipinputstream.closeEntry();
                    zipentry = zipinputstream.getNextEntry();
    
                }//while
    
                zipinputstream.close();
            }
            catch (Exception e)
           {
                e.printStackTrace();
           }
      }
    
    }
    

    Obviously this will not extract a folder tree because of the break statement. I tried to use recursion to process a folder tree but failed. Could someone show me how to improve this code to handle a folder tree instead of a compressed single level folder.

    • mikek
      mikek almost 15 years
      Chathuranga: Did Emre's answer fix your issue? If so, thank him by checking his answer =)
  • Emre Köse
    Emre Köse almost 15 years
    You may be right. In javadoc of isDirectory() it says "A directory entry is defined to be one whose name ends with a '/'". I edited my answer.