views:

2363

answers:

6

Hello Folks,

I have a file in .gz format. The java class for reading this file is GZIPInputStream. However, this class doesn't extend the BufferedReader class of java. As a result, I am not able to read the file line by line. I need something like this

reader  = new MyGZInputStream( some constructor of GZInputStream) 
reader.readLine()...

I though of creating my class which extends the Reader or BufferedReader class of java and use GZIPInputStream as one of its variable.

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.util.zip.GZIPInputStream;

public class MyGZFilReader extends Reader {

    private GZIPInputStream gzipInputStream = null;
    char[] buf = new char[1024];

    @Override
    public void close() throws IOException {
     gzipInputStream.close();
    }

    public MyGZFilReader(String filename)
               throws FileNotFoundException, IOException {
        gzipInputStream = new GZIPInputStream(new FileInputStream(filename));
    }

    @Override
    public int read(char[] cbuf, int off, int len) throws IOException {
     // TODO Auto-generated method stub
     return gzipInputStream.read((byte[])buf, off, len);
    }

}

But, this doesn't work when I use

BufferedReader in = new BufferedReader(
    new MyGZFilReader("F:/gawiki-20090614-stub-meta-history.xml.gz"));
System.out.println(in.readLine());

Can someone advice how to proceed ..

+1  A: 

What about:

GZIPInputStream zipReader = new GZIPInputStream();
InputStreamReader streamReader = new InputStreamReader(zipReader);
BufferedReader bufferedReader = new BufferedReader(streamReader);
Aaron
+3  A: 
GZIPInputStream gzip = new GZIPInputStream(new FileInputStream("F:/gawiki-20090614-stub-meta-history.xml.gz"));
BufferedReader br = new BufferedReader(new InputStreamReader(gzip));
br.readLine();
ChssPly76
Your answer is great. Short and concise .. However, erickson's answer is more detailed.
+6  A: 
erickson
thanks it worked... However, there is no need for reader step .. we can also write it asGZIPInputStream gzip = new GZIPInputStream(new FileInputStream("F:/gawiki-20090614-stub-meta-history.xml.gz")); BufferedReader br = new BufferedReader(new InputStreamReader(gzip));
A: 

You can't cast a char[] to a byte[] like you do here:

return gzipInputStream.read((byte[])buf, off, len);

This :

InputStream fileStream = new FileInputStream(filename);
InputStream gzipStream = new GZIPInputStream(fileStream);
Reader decoder = new InputStreamReader(gzipStream, encoding);
BufferedReader buffered = new BufferedReader(decoder);

from @erickson is the correct way to convert bytes to chars.

Clint
A: 

I'm doing this but it's too slow. Any way to make it faster?

devadvocate
BalusC
A: 

I would like to use Gzip in J2ME but GzipInputStream not support, please help me

duoichon