# 如何以 GZIP 格式压缩文件

> 原文： [https://beginnersbook.com/2014/07/how-to-compress-a-file-in-gzip-format/](https://beginnersbook.com/2014/07/how-to-compress-a-file-in-gzip-format/)

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

```java
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 here
      GZIPOutputStream gos = 
       new GZIPOutputStream(new FileOutputStream("B://Java/Myfile.gz"));

      //Specify location of Input file here
      FileInputStream fis = 
       new FileInputStream("B://Java/Myfile.txt");

      //Reading from input file and writing to output GZip file
      int 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(); 
     }
  }
}
```

**输出：**

```java
File Compressed!!
```

**参考：**
[GZIPOutputStream javadoc](https://docs.oracle.com/javase/7/docs/api/java/util/zip/GZIPOutputStream.html)