Java Reference
In-Depth Information
Solution
Use a
GZipInputStream
or
GZipOutputStream
as appropriate.
Discussion
The GNU
gzip
/
gunzip
utilities originated on Unix and are commonly used to compress files.
Unlike the ZIP format discussed in
Reading and Writing JAR or ZIP Archives
, these pro-
grams do not combine the functionality of archiving and compressing, and, therefore, they
are easier to work with. However, because they are not archives, people often use them in
conjunction with an archiver. On Unix,
tar
and
cpio
are common, with
tar
and
gzip
being the
de facto
standard combination. Many websites and FTP sites make files available with the
extension
.tar.gz
or
.tgz
; such files originally had to be first decompressed with
gunzip
and
then extracted with
tar
. As this became a common operation, modern versions of
tar
have
been extended to support a
-z
option, which means to
gunzip
before extracting, or to
gzip
be-
fore writing, as appropriate.
You may find archived files in
gzip
format on any platform. If you do, they're quite easy to
read, again using classes from the
java.util.zip
package. This program assumes that the
gzipped file originally contained text (Unicode characters). If not, you would treat it as a
stream of bytes (i.e., use a
BufferedInputStream
instead of a
BufferedReader
):
public
public class
class
ReadGZIP
ReadGZIP
{
public
public static
static
void
void
main
(
String
[]
argv
)
throws
throws
IOException
{
String FILENAME
=
"file.txt.gz"
;
// Since there are 4 constructor calls here, I wrote them out in full.
// In real life you would probably nest these constructor calls.
FileInputStream fin
=
new
new
FileInputStream
(
FILENAME
);
GZIPInputStream gzis
=
new
new
GZIPInputStream
(
fin
);
InputStreamReader xover
=
new
new
InputStreamReader
(
gzis
);
BufferedReader is
=
new
new
BufferedReader
(
xover
);
String line
;
// Now read lines of text: the BufferedReader puts them in lines,
// the InputStreamReader does Unicode conversion, and the
// GZipInputStream "gunzip"s the data from the FileInputStream.
while
while
((
line
=
is
.
readLine
()) !=
null
null
)
System
.
out
.
println
(
"Read: "
+
line
);
}
}