tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Zip Utilities > Read File From Zip File

Read File From Zip File 

The following example shows how to read a file from zip file. It iterates through all zip file entries until the exact file name match is found. It also shows how to convert stream to string.

File Name  :  
com/bethecoder/tutorials/utils/zip/ReadFromZipFile.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.utils.zip;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ReadFromZipFile {

  /**
   @param args
   @throws IOException 
   */
  public static void main(String[] args) {

    String srcZipFilePath = "C:\\abc.zip";
    String fileToRead = "TWO/FOUR/FIVE/abc.txt";
    
    readFromZipFile(srcZipFilePath, fileToRead);
  }
  
  public static void readFromZipFile(
      String srcZipFilePath, String fileToRead) {
    
    try {
      InputStream in = new FileInputStream(srcZipFilePath);
      ZipInputStream zin = new ZipInputStream(in);
      ZipEntry entry = null;
      String fileContent = null;
      
      while ((entry = zin.getNextEntry()) != null) {
        
        if (entry.getName().equals(fileToRead)) {
          fileContent = streamToString(zin);
          System.out.println("Found matching file : " + fileToRead);
          System.out.println("----------------------------------------");
          System.out.println(fileContent);
          break;
        else {
          System.out.println("No match found : " + entry.getName());
        }
        
        zin.closeEntry();
      }
      
      zin.close();
      
    catch (FileNotFoundException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    }
      
  }
  
  public static String streamToString(InputStream inputStream) {
    
    StringBuilder sb = new StringBuilder();
    BufferedReader br;

    try {
      br = new BufferedReader(new InputStreamReader(inputStream));
      String line;
      
      while ((line = br.readLine()) != null) {      
        sb.append(line).append("\n");
      }
      
    catch (Exception e) {
      e.printStackTrace();
    }
        
    return sb.toString();
  }
}
   

It gives the following output,
No match found : prop_xml_file.xml
No match found : test.txt
No match found : software.tsv
No match found : abc.txt
No match found : TWO/FOUR/
No match found : TWO/FOUR/FIVE/
Found matching file : TWO/FOUR/FIVE/abc.txt
----------------------------------------
Hello World 
Hello World2



 
  


  
bl  br