How to read text file from Zip Archive

package ZipExample;

import java.io.File;
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 read the file in Archive without extracting it.
 */
public class ReadFileInArchive {

	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();

		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());
			}
		}

		System.out
				.println("Enter the file name(With path) to see the content of the file ");
		String fileNameToView = scanner.next();
		for (Enumeration<? extends ZipEntry> e = zipfile.entries(); e
				.hasMoreElements();) {
			zipentry = e.nextElement();

			if (!zipentry.isDirectory()
					&& zipentry.getName().equals(fileNameToView)) {
				InputStream inputstream = zipfile.getInputStream(zipentry);
				String str = new java.util.Scanner(inputstream).useDelimiter(
						"\A").next();
				System.out.println("value in scanner str:" + str);
			}
		}

	}
}

 

By | 2012-09-25T03:16:40+00:00 September 25th, 2012|Code Base|1 Comment

About the Author:

One Comment

  1. Jacob May 30, 2015 at 12:11 pm - Reply

    Sir,
    I need to read an image file inside a zip file and the folder structure inside the zip file will be like evidimg.jpg. So now I want the solution to get the color code of the image inside the zip file without extracting it. Is it possible using java??

Leave A Comment