原文: https://beginnersbook.com/2014/07/how-to-compress-a-file-in-gzip-format/

    以下代码将指定的文件压缩为 GZip 格式。在下面的示例中,我们在B驱动器的Java文件夹下中有一个文本文件,我们正在压缩并生成同一文件夹中的 GZip 文件。

    1. import java.io.FileInputStream;
    2. import java.io.FileOutputStream;
    3. import java.io.IOException;
    4. import java.util.zip.GZIPOutputStream;
    5. public class GZipExample
    6. {
    7. public static void main( String[] args )
    8. {
    9. GZipExample zipObj = new GZipExample();
    10. zipObj.gzipMyFile();
    11. }
    12. public void gzipMyFile(){
    13. byte[] buffer = new byte[1024];
    14. try{
    15. //Specify Name and Path of Output GZip file here
    16. GZIPOutputStream gos =
    17. new GZIPOutputStream(new FileOutputStream("B://Java/Myfile.gz"));
    18. //Specify location of Input file here
    19. FileInputStream fis =
    20. new FileInputStream("B://Java/Myfile.txt");
    21. //Reading from input file and writing to output GZip file
    22. int length;
    23. while ((length = fis.read(buffer)) > 0) {
    24. /* public void write(byte[] buf, int off, int len):
    25. * Writes array of bytes to the compressed output stream.
    26. * This method will block until all the bytes are written.
    27. * Parameters:
    28. * buf - the data to be written
    29. * off - the start offset of the data
    30. * len - the length of the data
    31. */
    32. gos.write(buffer, 0, length);
    33. }
    34. fis.close();
    35. /* public void finish(): Finishes writing compressed
    36. * data to the output stream without closing the
    37. * underlying stream.
    38. */
    39. gos.finish();
    40. gos.close();
    41. System.out.println("File Compressed!!");
    42. }catch(IOException ioe){
    43. ioe.printStackTrace();
    44. }
    45. }
    46. }

    输出:

    1. File Compressed!!

    参考:

    GZIPOutputStream javadoc