java.util.zip.GZIPOutputStream.write(byte[] buf, int off, int len)方法範例

2019-10-16 22:32:57

java.util.zip.GZIPOutputStream.write(byte[] buf, int off, int len)方法將位元組陣列寫入壓縮輸出流。 該方法將阻塞,直到寫入所有位元組。

宣告

以下是java.util.zip.GZIPOutputStream.write(byte[] buf, int off, int len)方法的宣告。

public int write(byte[] buf, int off, int len)
   throws IOException

引數

  • buf - 要寫入的資料。
  • off - 資料的起始偏移量。
  • len - 資料的長度。

異常

  • IOException - 如果發生I/O錯誤。

範例

以下範例顯示了java.util.zip.GZIPOutputStream.write(byte[] buf, int off, int len)方法的用法。

package com.yiibai;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.zip.DataFormatException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZIPOutputStreamDemo {

   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to Tw511.com;"
         +"Welcome to Tw511.com;"
         +"Welcome to Tw511.com;"
         +"Welcome to Tw511.com;"
         +"Welcome to Tw511.com;"
         +"Welcome to Tw511.com;"
         +"Welcome to Tw511.com;"
         +"Welcome to Tw511.com;"
         +"Welcome to Tw511.com;"
         +"Welcome to Tw511.com;";

      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
      GZIPOutputStream outputStream = new GZIPOutputStream(arrayOutputStream);
      outputStream.write(input,0, input.length);
      outputStream.close();

      //Read and decompress the data
      byte[] readBuffer = new byte[5000];
      ByteArrayInputStream arrayInputStream = 
         new ByteArrayInputStream(arrayOutputStream.toByteArray());
      GZIPInputStream inputStream = new GZIPInputStream(arrayInputStream);
      int read = inputStream.read(readBuffer,0,readBuffer.length);
      inputStream.close();
      //Should hold the original (reconstructed) data
      byte[] result = Arrays.copyOf(readBuffer, read);

      // Decode the bytes into a String
      message = new String(result, "UTF-8");

      System.out.println("UnCompressed Message length : " + message.length());
   }
}

執行上面範例程式碼,得到以下結果 -

Original Message length : 300
UnCompressed Message length : 300