java.util.zip.DeflaterInputStream.read() 方法示例



描述

java.util.zip.DeflaterInputStream.read(byte[] b, int off, int len) 方法從輸入流讀取單個壓縮資料位元組。此方法將阻塞,直到可以讀取和壓縮某些輸入。

宣告

以下是 java.util.zip.DeflaterInputStream.read(byte[] b, int off, int len) 方法的宣告。

public int read(byte[] b, int off, int len)
   throws IOException

引數

  • b − 讀取資料的緩衝區。

  • off − b 內資料的起始偏移量。

  • len − 讀取到 b 中的最大壓縮位元組數。

返回值

實際讀取的位元組數,如果到達未壓縮輸入流的末尾則返回 -1。

異常

  • IndexOutOfBoundsException − 如果 len > b.length - off。

  • IOException − 如果發生 I/O 錯誤或此流已關閉。

示例

以下示例顯示了 java.util.zip.DeflaterInputStream.read(byte[] b, int off, int len) 方法的用法。

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;

public class DeflaterInputStreamDemo {
   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");
      int length = message.length();
	  
      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);
   
      ByteArrayInputStream bin = new ByteArrayInputStream(output);
      InflaterInputStream inflaterInputStream = new InflaterInputStream(bin);
      byte[] result = new byte[1024];

      inflaterInputStream.read(result,0,result.length);
      inflaterInputStream.close();
	  
      // Decode the bytes into a String
      String message1 = new String(result,0, length,"UTF-8");
      System.out.println(message.equals(message1));
   }
}

讓我們編譯並執行以上程式,這將產生以下結果:

Original Message length : 300
Total uncompressed bytes input :300
Compressed Message Checksum :368538129
Compressed Message length : 42
true
javazip_deflaterinputstream.htm
廣告