In the previous example we have learn how to compress a file in GZIP format. To get the file back to its original version we will now learn how to decompress the gzip file. Just like the previous example, we are also going to use the FileInputStream
and FileOutputStream
class to read the compressed source file and to write out the decompressed file. While GZipOutputStream
was used to create the gzip file, the GZipInputStream
is the class that handles the decompression.
Here is your code snippet:
package org.kodejava.util.zip;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
public class GZipDecompressExample {
public static void main(String[] args) {
// GZip input and output file.
String sourceFile = "output.gz";
String targetFile = "data-1.txt";
try (
// Create a file input stream to read the source file.
FileInputStream fis = new FileInputStream(sourceFile);
// Create a gzip input stream to decompress the source
// file defined by the file input stream.
GZIPInputStream gzis = new GZIPInputStream(fis);
// Create file output stream where the decompression result
// will be stored.
FileOutputStream fos = new FileOutputStream(targetFile)) {
// Create a buffer and temporary variable used during the
// file decompress process.
byte[] buffer = new byte[1024];
int length;
// Read from the compressed source file and write the
// decompress file.
while ((length = gzis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024