下面列出了怎么用java.util.zip.InflaterInputStream的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Returns an inflated copy of the input array.
* @throws IOException if the input cannot be properly decompressed
*/
public static final byte[] inflate(byte[] in) throws IOException {
// decompress using InflaterInputStream
ByteArrayOutputStream outStream =
new ByteArrayOutputStream(EXPECTED_COMPRESSION_RATIO * in.length);
InflaterInputStream inStream =
new InflaterInputStream ( new ByteArrayInputStream(in) );
byte[] buf = new byte[BUF_SIZE];
while (true) {
int size = inStream.read(buf);
if (size <= 0)
break;
outStream.write(buf, 0, size);
}
outStream.close();
return outStream.toByteArray();
}
public void streamChunk(byte[] data, RunnableVal<NBTStreamer> withStream) throws IOException {
if (data != null) {
try {
FastByteArrayInputStream nbtIn = new FastByteArrayInputStream(data);
FastByteArrayInputStream bais = new FastByteArrayInputStream(data);
InflaterInputStream iis = new InflaterInputStream(bais, new Inflater(), 1);
fieldBuf2.set(iis, byteStore2.get());
BufferedInputStream bis = new BufferedInputStream(iis);
NBTInputStream nis = new NBTInputStream(bis);
fieldBuf3.set(nis, byteStore3.get());
NBTStreamer streamer = new NBTStreamer(nis);
withStream.run(streamer);
streamer.readQuick();
} catch (IllegalAccessException unlikely) {
unlikely.printStackTrace();
}
}
}
@Override
synchronized public byte[] inflate(InputStream stream) throws IOException {
InflaterInputStream inputStream = new InflaterInputStream(stream);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(BUFFER_SIZE);
byte[] bufferOut;
int length;
try {
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
} finally {
outputStream.flush();
bufferOut = outputStream.toByteArray();
outputStream.close();
inputStream.close();
}
return bufferOut;
}
private InputStream urlToInputStream(URL url) throws IOException {
URLConnection conn = url.openConnection();
// pretend to be IE6
conn.setRequestProperty("User-Agent", IE);
// allow both GZip and Deflate (ZLib) encodings
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.connect();
String encoding = conn.getContentEncoding();
if ((encoding != null) && encoding.equalsIgnoreCase("gzip"))
return new GZIPInputStream(conn.getInputStream());
else if ((encoding != null) && encoding.equalsIgnoreCase("deflate"))
return new InflaterInputStream(conn.getInputStream(), new Inflater(
true));
else
return conn.getInputStream();
}
private static byte[] extractS2gsData( final File s2gsFile ) throws IOException {
final byte[] inBuffer = new byte[ 16 ];
try ( final FileInputStream fis = new FileInputStream( s2gsFile ) ) {
fis.read( inBuffer );
final ByteBuffer header = ByteBuffer.wrap( inBuffer ).order( ByteOrder.LITTLE_ENDIAN );
header.getInt(); // Magic word: "ZmpC" ("CmpZ" backward meaning: compressed with Zlib)
header.getInt(); // Zeros (reserved? version?)
final int size = header.getInt() ; // uncompressed data size
header.getInt(); // Zeros (reserved? version?)
try ( final InflaterInputStream compressedInputStream = new InflaterInputStream( fis ) ) {
final byte[] decompressed = new byte[ size ];
int pos = 0;
while ( pos < size )
pos += compressedInputStream.read( decompressed, pos, size - pos );
return decompressed;
}
}
}
/**
* unzip.
*
* @param bytes compressed byte array.
* @return byte uncompressed array.
* @throws IOException
*/
public static byte[] unzip(byte[] bytes) throws IOException
{
UnsafeByteArrayInputStream bis = new UnsafeByteArrayInputStream(bytes);
UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream();
InputStream is = new InflaterInputStream(bis);
try
{
IOUtils.write(is, bos);
return bos.toByteArray();
}
finally
{
is.close();
bis.close();
bos.close();
}
}
@ParameterizedTest
@ArgumentsSource(ClientAndProtocolProvider.class)
void testStrings_acceptEncodingDeflate(WebClient client) throws Exception {
final RequestHeaders req = RequestHeaders.of(HttpMethod.GET, "/strings",
HttpHeaderNames.ACCEPT_ENCODING, "deflate");
final CompletableFuture<AggregatedHttpResponse> f = client.execute(req).aggregate();
final AggregatedHttpResponse res = f.get();
assertThat(res.status()).isEqualTo(HttpStatus.OK);
assertThat(res.headers().get(HttpHeaderNames.CONTENT_ENCODING)).isEqualTo("deflate");
assertThat(res.headers().get(HttpHeaderNames.VARY)).isEqualTo("accept-encoding");
final byte[] decoded;
try (InflaterInputStream unzipper =
new InflaterInputStream(new ByteArrayInputStream(res.content().array()))) {
decoded = ByteStreams.toByteArray(unzipper);
}
assertThat(new String(decoded, StandardCharsets.UTF_8)).isEqualTo("Armeria is awesome!");
}
/**
* Decode the byte[] in base64 to a string.
*
* @param bytes the data to encode
* @return the new string in {@link #UTF8_ENCODING}.
*/
public static String decodeByteArrayToString(final byte[] bytes) {
final ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final byte[] buf = new byte[bytes.length];
try (final InflaterInputStream iis = new InflaterInputStream(bais)) {
int count = iis.read(buf);
while (count != -1) {
baos.write(buf, 0, count);
count = iis.read(buf);
}
return new String(baos.toByteArray(), Charset.forName(UTF8_ENCODING));
} catch (final Exception e) {
LOGGER.error("Base64 decoding failed", e);
return null;
}
}
@Test
void http() throws Exception {
final WebClient client =
WebClient.builder("http://127.0.0.1:" + dogma.serverAddress().getPort())
.setHttpHeader(HttpHeaderNames.AUTHORIZATION, "Bearer " + CsrfToken.ANONYMOUS)
.setHttpHeader(HttpHeaderNames.ACCEPT_ENCODING, "deflate")
.build();
final String contentPath = HttpApiV1Constants.PROJECTS_PREFIX + '/' + PROJ +
HttpApiV1Constants.REPOS + '/' + REPO +
"/contents" + PATH;
final AggregatedHttpResponse compressedResponse = client.get(contentPath).aggregate().join();
assertThat(compressedResponse.status()).isEqualTo(HttpStatus.OK);
final HttpData content = compressedResponse.content();
try (Reader in = new InputStreamReader(new InflaterInputStream(new ByteArrayInputStream(
content.array(), 0, content.length())), StandardCharsets.UTF_8)) {
assertThat(CharStreams.toString(in)).contains(CONTENT);
}
}
private static String zlibDeflate(final byte[] bytes) {
final ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final InflaterInputStream iis = new InflaterInputStream(bais);
final byte[] buf = new byte[1024];
try {
int count = iis.read(buf);
while (count != -1) {
baos.write(buf, 0, count);
count = iis.read(buf);
}
return new String(baos.toByteArray());
} catch (final Exception e) {
return null;
} finally {
IOUtils.closeQuietly(iis);
}
}
/**
* Base64 decodes the SAML message and then decompresses the message.
*
* @param message Base64 encoded, DEFALTE compressed, SAML message
*
* @return the SAML message
*
* @throws MessageDecodingException thrown if the message can not be decoded
*/
protected InputStream decodeMessage(String message) throws MessageDecodingException {
log.debug("Base64 decoding and inflating SAML message");
byte[] decodedBytes = Base64.decode(message);
if(decodedBytes == null){
log.error("Unable to Base64 decode incoming message");
throw new MessageDecodingException("Unable to Base64 decode incoming message");
}
try {
ByteArrayInputStream bytesIn = new ByteArrayInputStream(decodedBytes);
InflaterInputStream inflater = new InflaterInputStream(bytesIn, new Inflater(true));
return inflater;
} catch (Exception e) {
log.error("Unable to Base64 decode and inflate SAML message", e);
throw new MessageDecodingException("Unable to Base64 decode and inflate SAML message", e);
}
}
/**
* Decompresses the provided data, returning the inflated result.
*
* @param data the deflated picture data.
* @return the inflated picture data.
*/
private static byte[] inflatePictureData(byte[] data) {
try {
InflaterInputStream in = new InflaterInputStream(new ByteArrayInputStream(data));
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
int readBytes;
while ((readBytes = in.read(buf)) > 0) {
out.write(buf, 0, readBytes);
}
return out.toByteArray();
} catch (IOException e) {
log.log(POILogger.INFO, "Possibly corrupt compression or non-compressed data", e);
return data;
}
}
/**
* Decompresses the provided data, returning the inflated result.
*
* @param data the deflated picture data.
* @return the inflated picture data.
*/
private static byte[] inflatePictureData(byte[] data) {
try {
InflaterInputStream in = new InflaterInputStream(
new ByteArrayInputStream( data ) );
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
int readBytes;
while ((readBytes = in.read(buf)) > 0) {
out.write(buf, 0, readBytes);
}
return out.toByteArray();
} catch (IOException e) {
log.log(POILogger.WARN, "Possibly corrupt compression or non-compressed data", e);
return data;
}
}
public static byte[] inflate(InputStream stream) throws IOException {
InflaterInputStream inputStream = new InflaterInputStream(stream);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
try {
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
} finally {
buffer = outputStream.toByteArray();
outputStream.flush();
outputStream.close();
inputStream.close();
}
return buffer;
}
/**
* 解压缩
* @param is 输入流
* @return byte[] 解压缩后的数据
*/
public static byte[] decompress(InputStream is) {
InflaterInputStream iis = new InflaterInputStream(is);
ByteArrayOutputStream o = new ByteArrayOutputStream(1024);
byte[] result = null;
try {
int i = 1024;
byte[] buf = new byte[i];
while ((i = iis.read(buf, 0, i)) > 0) {
o.write(buf, 0, i);
}
result = o.toByteArray();
o.close();
iis.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public byte[] decompress(byte[] compressedData) throws JoseException
{
Inflater inflater = new Inflater(true);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (InflaterInputStream iis = new InflaterInputStream(new ByteArrayInputStream(compressedData), inflater))
{
int bytesRead;
byte[] buff = new byte[256];
while ((bytesRead = iis.read(buff)) != -1)
{
byteArrayOutputStream.write(buff, 0, bytesRead);
}
return byteArrayOutputStream.toByteArray();
}
catch (IOException e)
{
throw new JoseException("Problem decompressing data.", e);
}
}
/**
* 解压缩
*
* @param is 输入流
* @return byte[] 解压缩后的数据
*/
public static byte[] decompress(InputStream is)
{
InflaterInputStream iis = new InflaterInputStream(is);
ByteArrayOutputStream o = new ByteArrayOutputStream(BUFFER_LENGTH);
try
{
byte[] buf = new byte[BUFFER_LENGTH];
int len = -1;
while ((len = iis.read(buf)) != -1)
{
o.write(buf, 0, len);
}
}
catch (IOException e)
{
e.printStackTrace();
}
return o.toByteArray();
}
private final static String decompressString(byte[] str) {
// If compression is disabled, then the byte array is just a UTF-8 string
if(!RCRuntime.ENABLE_DEFLATE_COMPRESSION) {
return new String(str);
}
InflaterInputStream dis = new InflaterInputStream(new ByteArrayInputStream(str));
try {
return readIntoString(dis);
} catch (IOException e) {
e.printStackTrace();
log.severe("Error on decompress", e, null);
throw new RuntimeException(e);
}
}
/**
* A helper to FlateDecode.
*
* @param in the input data
* @param strict <CODE>true</CODE> to read a correct stream. <CODE>false</CODE> to try to read a
* corrupted stream
* @return the decoded data
*/
public static byte[] FlateDecode(byte in[], boolean strict) {
ByteArrayInputStream stream = new ByteArrayInputStream(in);
InflaterInputStream zip = new InflaterInputStream(stream);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte b[] = new byte[strict ? 4092 : 1];
try {
int n;
while ((n = zip.read(b)) >= 0) {
out.write(b, 0, n);
}
zip.close();
out.close();
return out.toByteArray();
} catch (Exception e) {
if (strict) {
return null;
}
return out.toByteArray();
}
}
/** A helper to FlateDecode.
* @param in the input data
* @param strict <CODE>true</CODE> to read a correct stream. <CODE>false</CODE>
* to try to read a corrupted stream
* @return the decoded data
*/
public static byte[] FlateDecode(byte in[], boolean strict) {
ByteArrayInputStream stream = new ByteArrayInputStream(in);
InflaterInputStream zip = new InflaterInputStream(stream);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte b[] = new byte[strict ? 4092 : 1];
try {
int n;
while ((n = zip.read(b)) >= 0) {
out.write(b, 0, n);
}
zip.close();
out.close();
return out.toByteArray();
}
catch (Exception e) {
if (strict)
return null;
return out.toByteArray();
}
}
public static String decompress(final byte[] bytes) throws IOException {
final InputStream in = new InflaterInputStream(new ByteArrayInputStream(bytes));
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final byte[] buffer = new byte[8192];
int len;
while ((len = in.read(buffer)) > 0) {
baos.write(buffer, 0, len);
}
return new String(baos.toByteArray(), "ISO-8859-1");
}
public static void readCompressedObject(@Nonnull final byte[] src, final int offset,
final int length, @Nonnull final Externalizable dst)
throws IOException, ClassNotFoundException {
FastByteArrayInputStream bis = new FastByteArrayInputStream(src, offset, length);
final InflaterInputStream iis = new InflaterInputStream(bis);
try {
readObject(iis, dst);
} finally {
IOUtils.closeQuietly(iis);
}
}
/**
* unzip.
*
* @param bytes compressed byte array.
* @return byte uncompressed array.
* @throws IOException
*/
public static byte[] unzip(byte[] bytes) throws IOException {
UnsafeByteArrayInputStream bis = new UnsafeByteArrayInputStream(bytes);
UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream();
InputStream is = new InflaterInputStream(bis);
try {
IOUtils.write(is, bos);
return bos.toByteArray();
} finally {
is.close();
bis.close();
bos.close();
}
}
private static byte[] inflate(byte[] b) throws IOException {
InputStream bais = new ByteArrayInputStream(b);
InputStream iis = new InflaterInputStream(bais);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c;
try {
while ((c = iis.read()) != -1) {
baos.write(c);
}
} finally {
iis.close();
}
return baos.toByteArray();
}
private byte[] inflate(byte[] compressedData) {
byte[] result = null;
if (compressedData != null) {
try {
ByteArrayInputStream source = new ByteArrayInputStream(compressedData);
DataInputStream headerIn = new DataInputStream(source);
int version = headerIn.readInt();
if (version > mCurrentBlobVersion) {
Log.w(TAG, "Saved payload from unrecognized version " + version);
return null;
}
InflaterInputStream in = new InflaterInputStream(source);
ByteArrayOutputStream inflated = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int nRead;
while ((nRead = in.read(buffer)) > 0) {
inflated.write(buffer, 0, nRead);
}
in.close();
inflated.flush();
result = inflated.toByteArray();
if (DEBUG) {
Log.v(TAG, "Inflated " + compressedData.length + " bytes to " + result.length);
}
} catch (IOException e) {
// result is still null here
Log.w(TAG, "Unable to process restored payload: " + e.getMessage());
}
}
return result;
}
private static byte[] readBytes(InflaterInputStream inflaterInputStream, int length) throws IOException {
byte[] buffer = new byte[length];
int bytesRead = 0;
while (bytesRead < length) {
int len = inflaterInputStream.read(buffer, bytesRead, length - bytesRead);
if (len == -1) {
throw new IOException("End of compressed data has reached");
} else {
bytesRead += len;
}
}
return buffer;
}
public static byte[] zlibDecompress(byte[] input) {
InflaterInputStream inflater = new InflaterInputStream(new ByteArrayInputStream(input));
try {
return IOUtils.toByteArray(inflater);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Could not decompress");
}
return new byte[0];
}
DeflateInputStream(Hessian2Input in)
throws IOException
{
_in = in;
int len = in.readInt();
if (len != 0)
throw new IOException("expected no headers");
_bodyIn = _in.readInputStream();
_inflateIn = new InflaterInputStream(_bodyIn);
}
private static byte[] inflate(String data) throws Exception {
byte[] compressed = Base64.getDecoder().decode(data);
ByteArrayInputStream in = new ByteArrayInputStream(compressed);
InflaterInputStream inf = new InflaterInputStream(in, new Inflater(true));
byte[] byteArray = IOUtils.toByteArray(inf);
return byteArray;
}
private static byte[] readBytes(InflaterInputStream inflaterInputStream, int length) throws IOException {
byte[] buffer = new byte[length];
int bytesRead = 0;
while (bytesRead < length) {
int len = inflaterInputStream.read(buffer, bytesRead, length - bytesRead);
if (len == -1) {
throw new IOException("End of compressed data has reached");
} else {
bytesRead += len;
}
}
return buffer;
}