The core of a streaming gzip operation is small: read a buffer, write the bytes that were read, and finish the compression stream. The original helper used an 8 KiB buffer for both compression and decompression.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* Original example, 2016-07-22.
*/
public class GZipFile {
public static int BUFFER_SIZE = 8 * 1024;
private static GZipFile instance = new GZipFile();
public static GZipFile getInstance() {
return instance;
}
/**
* GZip it
*/
public void gzipIt(String sourceFile, String ouputGzipFile) {
byte[] buffer = new byte[BUFFER_SIZE];
try {
GZIPOutputStream gzos =
new GZIPOutputStream(new FileOutputStream(ouputGzipFile));
FileInputStream in =
new FileInputStream(sourceFile);
int len;
while ((len = in.read(buffer)) > 0) {
gzos.write(buffer, 0, len);
}
in.close();
gzos.finish();
gzos.close();
System.out.println("Done");
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* GunZip it
*/
public void gunzipIt(String inputGzipFile, String outputFile) {
byte[] buffer = new byte[BUFFER_SIZE];
try {
GZIPInputStream gzis =
new GZIPInputStream(new FileInputStream(inputGzipFile));
FileOutputStream out =
new FileOutputStream(outputFile);
int len;
while ((len = gzis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
gzis.close();
out.close();
System.out.println("Done");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Watch the error path
The helper closes its streams on the ordinary completion path and prints exceptions on failure. An exception can skip those explicit closes, and the void methods give the caller no reliable success result. A printed Done also does not validate the intended file contents.
This is an older implementation record. Resource cleanup, partial destination files, input size, and error propagation need review before adapting it; no files were compressed or restored for this revision.