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.zaixian;
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 xuhuhu.com;"
+"Welcome to xuhuhu.com;"
+"Welcome to xuhuhu.com;"
+"Welcome to xuhuhu.com;"
+"Welcome to xuhuhu.com;"
+"Welcome to xuhuhu.com;"
+"Welcome to xuhuhu.com;"
+"Welcome to xuhuhu.com;"
+"Welcome to xuhuhu.com;"
+"Welcome to xuhuhu.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
