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



描述

java.util.zip.InflaterInputStream.read(byte[] buf, int off, int len) 方法將未壓縮的資料讀取到位元組陣列中。如果 len 不為零,則該方法將阻塞,直到可以解壓縮某些輸入;否則,不讀取任何位元組並返回 0。

宣告

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

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

引數

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

  • off − 目標陣列 b 中的起始偏移量。

  • len − 讀取的位元組最大數量。

返回值

實際讀取的位元組數,如果到達壓縮輸入的末尾或需要預設字典,則返回 -1。

異常

  • NullPointerException − 如果 buf 為 null。

  • IndexOutOfBoundsException − 如果 off 為負數,len 為負數,或 len 大於 buf.length - off。

  • ZipException − 如果發生 ZIP 格式錯誤。

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

示例

以下示例演示了 java.util.zip.InflaterInputStream.read(byte[] buf, 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 InflaterInputStreamDemo {
   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_inflaterinputstream.htm
廣告
© . All rights reserved.