Data Compression
The java.util.zip
package contains classes you can use for data compression. In this
section, we’ll talk about how to use these classes. We’ll
also present two useful example programs that build on what you have
just learned about streams and files.
The classes in the
java.util.zip
package support two widespread
compression formats: GZIP and ZIP. Both of these are based on the
ZLIB compression algorithm, which
is
discussed in RFC 1950, RFC
1951, and RFC 1952. These documents are available at http://www.faqs.org/rfcs. But you don’t
need to read them unless you want to implement your own compression
algorithm or otherwise extend the functionality of the
java.util.zip package.
Compressing Data
The java.util.zip class provides two
FilterOutputStream subclasses to write compressed
data to a stream. To write compressed data in the GZIP format, simply
wrap
a GZIPOutputStream
around an underlying stream and write to it. The following is a
complete example that shows how to compress a file using the GZIP
format:
//file: GZip.java import java.io.*; import java.util.zip.*; public class GZip { public static int sChunk = 8192; public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: GZip source"); return; } // create output stream String zipname = args[0] + ".gz"; GZIPOutputStream zipout; try { FileOutputStream out = new FileOutputStream(zipname); zipout = new GZIPOutputStream(out); } catch (IOException e) { System.out.println("Couldn't ...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.
Read now
Unlock full access