Friday, 1 July 2016

Unzipping files in Java

The package provides classes for data compression and decompression. For decompressing a ZIP file you need to read data from an input stream. In the package ZipInputStream class is there for reading ZIP files.

Once ZIP input stream is opened, you can read the zip entries using the getNextEntry method which returns a ZipEntry object. If the end-of-file is reached, getNextEntry returns null.

While going through the zip entries you can check whether that entry is for a directory or for a file, if it is a directory just create the folder in destination. If it is a file then you need to read the data to the output file by opening an OutputStream.

Java program for unzipping


public class Unzip {

    static final int BUFFER = 2048;
    // Output folder
     private static final String DEST_FOLDER = "G://Output";
       public static void main (String argv[]) {
          try {
              File folder = new File(DEST_FOLDER);
             BufferedOutputStream dest = null;
             // zipped input
             FileInputStream fis = new FileInputStream("G://");
             ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
             ZipEntry entry;
             while((entry = zis.getNextEntry()) != null) {
                System.out.println("Extracting: " +entry);
                int count;
                byte data[] = new byte[BUFFER];
                String fileName = entry.getName();
                File newFile = new File(folder + File.separator + fileName);
                // If directory then just create the directory (and parents if required)
                // write the files to the disk
                FileOutputStream fos = new FileOutputStream(newFile);
                dest = new BufferedOutputStream(fos, BUFFER);
                while ((count =, 0, BUFFER)) != -1) {
                   dest.write(data, 0, count);
          } catch(Exception e) {

Note that though here output folder is taken as a separate folder with different name, but you can also derive that name using the input folder name.

That's all for this topic Unzipping files in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Related Topics

  1. How to find last modified date of a file in Java
  2. How to read file from the last line in Java
  3. Reading file in Java using BufferedReader
  4. Reading file in Java using Scanner

You may also like -

>>>Go to Java Programs page

1 comment:

  1. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.

    ccna training in chennai Adyar