Sobes.tech
Middle

Which classes in Java support reading and writing streams in compressed format?

sobes.tech AI

Answer from AI

Java uses classes from the java.util.zip and java.util.jar packages for working with compressed streams.

Main classes:

  • GZIPInputStream and GZIPOutputStream: For working with the GZIP format.
  • ZipInputStream and ZipOutputStream: For working with the ZIP format.
  • DeflaterInputStream and DeflaterOutputStream: Use the DEFLATE algorithm (the basis of GZIP and ZIP, but without metadata).

Example of reading GZIP:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;

public class GzipReader {
    public static void main(String[] args) throws IOException {
        try (GZIPInputStream gis = new GZIPInputStream(new FileInputStream("file.gz"))) {
            int data = gis.read();
            while (data != -1) {
                // Processing read data
                System.out.print((char) data);
                data = gis.read();
            }
        }
    }
}

Example of writing to GZIP:

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

public class GzipWriter {
    public static void main(String[] args) throws IOException {
        String content = "This is some data to be compressed.";
        try (GZIPOutputStream gos = new GZIPOutputStream(new FileOutputStream("file.gz"))) {
            gos.write(content.getBytes());
        }
    }
}

Similar principles apply to ZipInputStream and ZipOutputStream classes, but they work with entries inside ZIP archives.

These classes are wrappers over regular input/output streams (InputStream, OutputStream) and automatically perform compression/decompression.