📜  java.util.zip-GZIPInputStream类(1)

📅  最后修改于: 2023-12-03 15:01:35.688000             🧑  作者: Mango

Java.util.zip GZIPInputStream Class

The GZIPInputStream class in java.util.zip provides a way to decompress data that has been compressed using the GZIP algorithm.

Constructor

The class has a single constructor that takes an InputStream object as a parameter:

public GZIPInputStream(InputStream in) throws IOException
Methods

The GZIPInputStream class contains several methods that allow you to work with compressed data. Some of the most commonly used methods are:

close()

Closes the input stream:

public void close() throws IOException
read(byte[] buffer, int offset, int length)

Reads up to length bytes from the input stream and stores them in the specified buffer starting at offset. Returns the number of bytes read, or -1 if the end of the input stream has been reached:

public int read(byte[] buffer, int offset, int length) throws IOException
skip(long n)

Skips over and discards up to n bytes of data from the input stream:

public long skip(long n) throws IOException
Example Usage
try (InputStream fileIn = new FileInputStream("compressedFile.gz");
        GZIPInputStream gzipIn = new GZIPInputStream(fileIn)) {
            
    byte[] buffer = new byte[1024];
    int len;
    while ((len = gzipIn.read(buffer)) > 0) {
        // do something with decompressed data
    }
} catch (IOException e) {
    e.printStackTrace();
}

In the example above, we open a file input stream to a compressed file, then create a GZIPInputStream instance to decompress the data. We then read the decompressed data into a buffer and process it. Finally, we close the input streams in a try-with-resources block to ensure they are properly closed even in the event of an exception being thrown.