Working with GZip Archives in Java

Overview

Aspose.ZIP for Java API lets work with creating and managing GZip archives in your applications without the need of any other 3rd party applications. Aspose.ZIP API provides  GZipArchive class to work with GZip archives. This class provides various methods to perform operations on archives.

Gzip compression algorithm is based on the DEFLATE algorithm, which is a combination of LZ77 and Huffman coding.

Compress A File

The following code example shows how to compress a file using GZipArchive instance.

1try (GzipArchive archive = new GzipArchive()) {
2    archive.setSource(dataDir + "data.bin");
3    archive.save(dataDir + "archive.gz");
4}

Open GZIP Archive

The following code example shows how to open a GZip archive.

 1try (GzipArchive archive = new GzipArchive(dataDir + "archive.gz")) {
 2    try (FileOutputStream extracted = new FileOutputStream(dataDir + "data.bin")) {
 3        InputStream unpacked = archive.open();
 4        byte[] b = new byte[8192];
 5        int bytesRead;
 6        while (0 < (bytesRead = unpacked.read(b, 0, b.length))) {
 7            extracted.write(b, 0, bytesRead);
 8        }
 9    }
10} catch (IOException ex) {
11    System.out.println(ex);
12}

Extract to Output Stream

The following code example shows how to open an archive from a stream and extract it to a ByteArrayOutputStream.

 1ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
 2try (GzipArchive archive = new GzipArchive(new FileInputStream(dataDir + "sample.gz"))) {
 3    byte[] b = new byte[8192];
 4    int bytesRead;
 5    InputStream archiveStream = archive.open();
 6    while (0 < (bytesRead = archiveStream.read(b, 0, b.length))) {
 7        outputStream.write(b, 0, bytesRead);
 8    }
 9    System.out.println(archive.getName());
10} catch (IOException ex) {
11    System.out.println(ex);
12}

Save to Output Stream

The following code example shows how to open and save to OutputStream.

1ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
2try (GzipArchive archive = new GzipArchive()) {
3    archive.setSource(new File(dataDir + "data.bin"));
4    archive.save(outputStream);
5}
Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.