java.util.zip.GZIPInputStream.read(byte[] buf, int off, int len)
方法將未壓縮的資料讀入一個位元組陣列。 如果len
不為零,該方法將阻塞,直到某些輸入可以被解壓; 否則,不讀取位元組並返回0
。
以下是java.util.zip.GZIPInputStream.read(byte[] buf, int off, int len)
方法的宣告。
public int read(byte[] buf, int off, int len)
throws IOException
引數
buf
- 資料讀入的緩衝區。off
- 目標陣列buf中的起始偏移量。len
- 讀取的最大位元組數。返回值
-1
。異常
NullPointerException
- 如果buf
是null
。IndexOutOfBoundsException
- 如果off
是負數,len
是負數,或者len
大於buf.length-off
。ZipException
- 如果壓縮的輸入資料已損壞。IOException
- 如果發生I/O錯誤。範例
以下範例顯示了java.util.zip.GZIPInputStream.read(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 GZIPInputStreamDemo {
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);
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