import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class ZipUtils
{
/**
* Compresses the input byte array using GZIP.
*
* @param binaryInput Array of bytes that should be compressed.
* @return Compressed bytes
* @throws IOException
*/
public static byte[] gzip(byte[] binaryInput) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
gzipOut.write(binaryInput);
gzipOut.finish();
gzipOut.close();
return baos.toByteArray();
}
/**
* Decompresses the input stream using GZIP.
*
* @param inputStream Stream those content should be decompressed.
* @return Decompressed bytes
* @throws IOException
*/
public static byte[] gunzip(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int count;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPInputStream gzipIn = new GZIPInputStream(inputStream);
while ((count = gzipIn.read(buffer)) != -1) {
baos.write(buffer, 0, count);
}
gzipIn.close();
return baos.toByteArray();
}
/**
* Decompresses the input byte array using GZIP.
*
* @param binaryInput Array of bytes that should be decompressed.
* @return Decompressed bytes
* @throws IOException
*/
public static byte[] gunzip(byte[] binaryInput) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(binaryInput);
return gunzip(bais);
}
}
压缩字节流类
最新推荐文章于 2022-12-28 14:38:56 发布
本文介绍了一个实用的Java工具类,用于实现GZIP压缩和解压缩功能。该工具类提供了将字节数组进行GZIP压缩和解压缩的方法,并能够处理输入流的解压缩。适用于需要在网络传输中减小数据体积或存储时节省空间的应用场景。
1712

被折叠的 条评论
为什么被折叠?



