zlib 介绍
有关ZLib可参见官方主页 http://www.zlib.net/
ZLib可以简单的理解为 数据 压缩、解压缩算法,如:对字节数组进行压缩
与 zip 不同,zip可以对文件、目录进行压缩
代码
package top.malaoshi.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.*;
public class ZLibUtils {
static final int MAX_LEN = 1024 * 8;
/**
* 压缩
*
* @param data
* 待压缩数据
* @return byte[] 压缩后的数据
*/
public static byte[] compress(byte[] data) throws IOException {
byte[] output = null;
Deflater compresser = new Deflater();
compresser.reset();
compresser.setInput(data);
compresser.finish();
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);
try {
byte[] buf = new byte[MAX_LEN];
while (!compresser.finished()) {
int i = compresser.deflate(buf);
bos.write(buf, 0, i);
}
output = bos.toByteArray();
} finally {
bos.close();
}
compresser.end();
return output;
}
/**
* 压缩
*
* @param data 待压缩数据
*
* @param os 输出流
*/
public static void compress(byte[] data, OutputStream os) throws IOException {
DeflaterOutputStream dos = new DeflaterOutputStream(os);
dos.write(data, 0, data.length);
dos.finish();
dos.flush();
dos.close();
}
/**
* 解压缩
*
* @param data
* 待压缩的数据
* @return byte[] 解压缩后的数据
*/
public static byte[] decompress(byte[] data) throws IOException, DataFormatException {
byte[] output = null;
Inflater decompresser = new Inflater();
decompresser.reset();
decompresser.setInput(data);
ByteArrayOutputStream o = new ByteArrayOutputStream(data.length);
try {
byte[] buf = new byte[MAX_LEN];
while (!decompresser.finished()) {
int i = decompresser.inflate(buf);
o.write(buf, 0, i);
}
output = o.toByteArray();
} finally {
o.close();
}
decompresser.end();
return output;
}
/**
* 解压缩
*
* @param is
* 输入流
* @return byte[] 解压缩后的数据
*/
public static byte[] decompress(InputStream is) throws IOException {
InflaterInputStream iis = new InflaterInputStream(is);
ByteArrayOutputStream o = new ByteArrayOutputStream(MAX_LEN);
try {
int i = MAX_LEN;
byte[] buf = new byte[i];
while ((i = iis.read(buf, 0, i)) > 0) {
o.write(buf, 0, i);
}
} catch (IOException e) {
throw e;
} finally {
iis.close();
o.close();
}
return o.toByteArray();
}
}
参考:
https://blog.csdn.net/wxyFighting/article/details/9075505