原文: https://beginnersbook.com/2014/07/how-to-compress-a-file-in-gzip-format/
以下代码将指定的文件压缩为 GZip 格式。在下面的示例中,我们在B驱动器的Java文件夹下中有一个文本文件,我们正在压缩并生成同一文件夹中的 GZip 文件。
import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.GZIPOutputStream;public class GZipExample{public static void main( String[] args ){GZipExample zipObj = new GZipExample();zipObj.gzipMyFile();}public void gzipMyFile(){byte[] buffer = new byte[1024];try{//Specify Name and Path of Output GZip file hereGZIPOutputStream gos =new GZIPOutputStream(new FileOutputStream("B://Java/Myfile.gz"));//Specify location of Input file hereFileInputStream fis =new FileInputStream("B://Java/Myfile.txt");//Reading from input file and writing to output GZip fileint length;while ((length = fis.read(buffer)) > 0) {/* public void write(byte[] buf, int off, int len):* Writes array of bytes to the compressed output stream.* This method will block until all the bytes are written.* Parameters:* buf - the data to be written* off - the start offset of the data* len - the length of the data*/gos.write(buffer, 0, length);}fis.close();/* public void finish(): Finishes writing compressed* data to the output stream without closing the* underlying stream.*/gos.finish();gos.close();System.out.println("File Compressed!!");}catch(IOException ioe){ioe.printStackTrace();}}}
输出:
File Compressed!!
参考:
