How to extract zip file with subdirectories

package ZipExample;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

/*
 * Here we will learn to extract Zip Archive
 */
public class ExtractZipArchive {

	public static void main(String[] args) throws ZipException, IOException {

		Scanner scanner = new Scanner(System.in);
		System.out
				.println("Enter the location of Zip file to read(Along with file name)");
		String zipFileLocation = scanner.next();

		System.out.println("Enter the path where you want to extract this Zip");
		String extractFileLocation = scanner.next();

		File file = new File(zipFileLocation);
		ZipFile zipfile = new ZipFile(file);

		ZipEntry zipentry;

		System.out.println("nList of files in zip archive");
		int fileNumber = 0;
		for (Enumeration<? extends ZipEntry> e = zipfile.entries(); e
				.hasMoreElements(); fileNumber++) {
			zipentry = e.nextElement();

			if (!zipentry.isDirectory()) {

				System.out.println(fileNumber + "-" + zipentry.getName());

				File fileFile = new File(extractFileLocation + "\"
						+ zipentry.getName());

				if (!fileFile.exists()) {
					System.out
							.println("File doesn't exist, Hence creating file");
					fileFile.createNewFile();
				}

				InputStream inputstream = zipfile.getInputStream(zipentry);
				String str = new java.util.Scanner(inputstream).useDelimiter(
						"\A").next();

				BufferedWriter bw = new BufferedWriter(new FileWriter(fileFile));
				bw.append(str);
				bw.close();

			} else {
				File fileDirectory = new File(extractFileLocation + "\"
						+ zipentry.getName());
				fileDirectory.mkdir();
			}

			System.out.println("Zip File Extracted");
		}

	}
}

 

By | 2012-09-25T03:14:36+00:00 September 25th, 2012|Code Base|0 Comments

About the Author:

Leave A Comment