1.數(shù)據(jù)壓縮算法你用過幾種?
之前知道壓縮有文件類ZIP吏够,GZIP,圖片類,質(zhì)量壓縮播急,采樣率壓縮等,當(dāng)然圖片也是文件的一種售睹,類似于采樣率壓縮只適合圖片類;
這些說出來后昌妹,估計大牛們會吐槽:“真low,就知道這點飞崖,市面上有好多開源的烂叔,分分鐘給你寫個固歪。。牢裳。》〗。”胞四。
確實市面上開源的或已集成近個語言開發(fā)的sdk中有很多伶椿。。脊另。导狡。
簡要統(tǒng)計了下有如下一些:
ZLIB偎痛、GZIP、BZIP踩麦、snappy、LZO谓谦、LZF贫橙、FastLZ和QuickLZ等等
那么他們有什么不同呢反粥?
ZLIB疲迂,GZIP采用DEFLATE壓縮,那DEFLATE又是什么呢
DEFLATE是同時使用了LZ77算法與哈夫曼編碼(Huffman Coding)的一個無損數(shù)據(jù)壓縮算法尤蒿;
jdk中對zlib壓縮庫提供了支持,壓縮類Deflater和解壓類Inflater幅垮,Deflater和Inflater都提供了native方法
private native int deflateBytes(long addr, byte[] b, int off, int len,
int flush);
private native int inflateBytes(long addr, byte[] b, int off, int len)
throws DataFormatException;
所有可以直接使用jdk提供的壓縮類Deflater和解壓類Inflater,代碼如下:
public static byte[] compress(byte input[]) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Deflater compressor = new Deflater(1);
try {
compressor.setInput(input);
compressor.finish();
final byte[] buf = new byte[2048];
while (!compressor.finished()) {
int count = compressor.deflate(buf);
bos.write(buf, 0, count);
}
} finally {
compressor.end();
}
return bos.toByteArray();
}
public static byte[] uncompress(byte[] input) throws DataFormatException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Inflater decompressor = new Inflater();
try {
decompressor.setInput(input);
final byte[] buf = new byte[2048];
while (!decompressor.finished()) {
int count = decompressor.inflate(buf);
bos.write(buf, 0, count);
}
} finally {
decompressor.end();
}
return bos.toByteArray();
}
可以指定算法的壓縮級別巩螃,這樣你可以在壓縮時間和輸出文件大小上進(jìn)行平衡∝罢可選的級別有0(不壓縮)爷耀,以及1(快速壓縮)到9(慢速壓縮),這里使用的是以速度為優(yōu)先。
GZIP只是在deflate格式上增加了文件頭和文件尾歹叮,同樣jdk也對gzip提供了支持跑杭,分別是GZIPOutputStream和GZIPInputStream類咆耿,同樣可以發(fā)現(xiàn)GZIPOutputStream是繼承于DeflaterOutputStream的,GZIPInputStream繼承于InflaterInputStream萨螺,并且可以在源碼中發(fā)現(xiàn)writeHeader和writeTrailer方法:
private void writeHeader() throws IOException {
......
}
private void writeTrailer(byte[] buf, int offset) throws IOException {
......
}
bzip2是Julian Seward開發(fā)并按照自由軟件/開源軟件協(xié)議發(fā)布的數(shù)據(jù)壓縮算法及程序。Seward在1996年7月第一次公開發(fā)布了bzip2 0.15版慰技,在隨后幾年中這個壓縮工具穩(wěn)定性得到改善并且日漸流行椭盏,Seward在2000年晚些時候發(fā)布了1.0版吻商。
bzip2比傳統(tǒng)的gzip的壓縮效率更高,但是它的壓縮速度較慢艾帐。
jdk中沒有對bzip2實現(xiàn),不過在commons-compress中進(jìn)行了實現(xiàn)柒爸,maven引入:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.12</version>
</dependency>
未完待續(xù)准浴,揍鸟,句旱,,