Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Reading and Writing Compressed Files

Problem

You need to read or write files that have been compressed using GNU zip, or gzip. These files are usually saved with the extension .gz.

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 PkZip format discussed in Section 9.19, these programs do not combine the functionality of archiving and compressing, and are therefore 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 web sites and FTP sites make files available with the extension .tar.gz; 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 before 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, that is, use a BufferedInputStream instead of a BufferedReader.

import java.io.*; import java.util.zip.*; public class ReadGZIP { public static void main(String ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata