Extract Zip File Java

Extract Zip File Java

Below is sample program which shows how to extract (Decompress) zip file using Java. We will use java.util.zip Package to unzip files.

  • Sample java program:
package com.javahonk;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnZipFileJava {

	private static final int BUFFER = 2048;
	private static final String ZIP_FILE_NAME = "C:\\JavaHonk\\zip\\createWarFile.zip";
	private static final String OUTPUT_FOLDER_NAME = "C:\\JavaHonk\\zip\\Unzip";

	public static void main(String argv[]) {
		
		try {
			
			File outPutFile = new File(OUTPUT_FOLDER_NAME);
			
			//Create output folder if not exists
			if (!outPutFile.exists()) {
				outPutFile.mkdir();
			}
			
			BufferedOutputStream dest = null;
			FileInputStream fis = new FileInputStream(ZIP_FILE_NAME);
			ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
			
			ZipEntry entry;
			
			while ((entry = zis.getNextEntry()) != null) {
				
				System.out.println("Extracting files: " + entry);				
				String fileName = entry.getName();
				
				File newFile = new File(OUTPUT_FOLDER_NAME + File.separator+ fileName);
				
				//Check if file is directory then just create don't need output stream
				if (entry.isDirectory()) {
					newFile.mkdir();
				}else {
					
					FileOutputStream fos = new FileOutputStream(newFile);
					
					int count;
					byte data[] = new byte[BUFFER];
					dest = new BufferedOutputStream(fos, BUFFER);
					
					while ((count = zis.read(data, 0, BUFFER)) != -1) {
						dest.write(data, 0, count);
					}
					dest.flush();
					dest.close();
				}
				
			}
			
			zis.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
  • Output:

Extract Zip File Java

For more information please refer oracle documentation here

Leave a Reply

Your email address will not be published. Required fields are marked *