What in case there are hundred of files in a folder you want to unzip. (We won't go into the details of why we want to unzip the files, when we can directly read the zipped version... That's another story).
Task: How to unzip a ".gz" file using Java.
Tools: Classes GZIPInputStream and OutputStream helps us to do the task.
GZIPInputStream gzipInputStream = new GZIPInputStream(newFileInputStream(inFilename));
OutputStream out = new FileOutputStream(outFilename);
byte[] buf = new byte[102400]; //size can be changed according to programmer's need.
int len;
while ((len = gzipInputStream.read(buf)) > 0) {
out.write(buf, 0, len);
}
OutputStream out = new FileOutputStream(outFilename);
byte[] buf = new byte[102400]; //size can be changed according to programmer's need.
int len;
while ((len = gzipInputStream.read(buf)) > 0) {
out.write(buf, 0, len);
}
The main points to note here are:-
a) GZIPInputStream class which creates a inputStream for the file to be read.
b) GZIPInputStream.read(buf) function, reads the uncompressed data into the buffer. The return type of this function is int, which specifies the number of bytes read.
c) The data read can be written into a FileOutputStream in uncompressed form.
So easy to unzip files.
------------------------
Kapil Dalwani
Hi Kapil,
ReplyDeleteI tried your code but it was not working.
It caused an Exception as follows:
---
Exception in thread "main" java.io.IOException: Corrupt GZIP trailer
at java.util.zip.GZIPInputStream.readTrailer(GZIPInputStream.java:177)
at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:89)
at java.io.FilterInputStream.read(FilterInputStream.java:90)
I'm getting the same error when trying to uncompress a gzipped bytearrayinputstream.
ReplyDeleteIt workerd for me. seems like Some thing wrong with your file.
ReplyDeleteConvert your file to gz using gzip command...and try
i am also getting same issue..when i am retrieving '*.gz' file from ftp...
ReplyDelete