In this example, let’s us see how to compress a file in GZIP format in Java.
Source Code
package com.beginner.examples;
import java.io.*;
import java.util.zip.GZIPOutputStream;
public class FileOperator29Example {
public static void main(String[] args) throws IOException{
File file = new File("example.txt");
FileInputStream fis = new FileInputStream(file);
GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream("example.gz"));
int len = 0;
byte[] buf = new byte[1024];
while ((len = fis.read(buf)) != -1)
{
gzos.write(buf, 0, len);
}
gzos.flush();
fis.close();
System.out.println("Done!");
}
}
Output:
Done!
References
Imported packages in Java documentation: