How to read gzip text file in Java

In the post How to read Text Files in Java. So how to read it if a text file is gzipped. Again Decorator Pattern comes to the rescue. We do minor changes to the program. Instead of using FileReader, we update the code as following

public void readGzippedFile(String fileName) throws IOException {

    System.out.println("Processing "+fileName);

    File fileTobeRead = new File(fileName);

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(fileTobeRead))));
    String line = null;
    while((line = bufferedReader.readLine()) != null) {
      processLine(line);
    }
  }

The highlighted lines shows the change. We get the InputStream and add GZipInputStream over it to deflate the compression. We use Reader as we know we shall be processing a text file. This is the only change needed to process gzipped files.

Everything Together

package com.codezuzu.algo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;

/**
 * codezuzu.com
 */
public class GzippedFileReader {


  public void readGzippedFile(String fileName) throws IOException {

    System.out.println("Processing "+fileName);

    File fileTobeRead = new File(fileName);

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(fileTobeRead))));
    String line = null;
    while((line = bufferedReader.readLine()) != null) {
      processLine(line);
    }
  }

  private void processLine(String line) {
    System.out.println(line);
  }

  public static void main(String[] args) throws IOException {
    GzippedFileReader textFileReading = new GzippedFileReader();
    textFileReading.readGzippedFile(args[0]);
  }
}

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.