package com.test.java.zip;import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;/**
@author jrwangxin1 字节数组压缩解压工具
/
public class ZipUtil {
/** 压缩 /
public static byte[] zip(byte[] source) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
zipOutputStream.putNextEntry(new ZipEntry("0"));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(zipOutputStream);
bufferedOutputStream.write(source);
bufferedOutputStream.close();
return byteArrayOutputStream.toByteArray();
}/** 解压 */
public static byte[] unzip(byte[] source) throws IOException {
ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(source));
while (zipInputStream.getNextEntry() != null) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();</span><span style="color: #0000ff">byte</span>[] buffer = <span style="color: #0000ff">new</span> <span style="color: #0000ff">byte</span>[4096<span style="color: #000000">]; </span><span style="color: #0000ff">int</span> i=0<span style="color: #000000">; </span><span style="color: #0000ff">while</span> ((i = zipInputStream.read(buffer)) != -1<span style="color: #000000">) { byteArrayOutputStream.write(buffer,</span>0<span style="color: #000000">,i); } </span><span style="color: #0000ff">return</span><span style="color: #000000"> byteArrayOutputStream.toByteArray(); } </span><span style="color: #0000ff">return</span> <span style="color: #0000ff">null</span><span style="color: #000000">;
}
public static void main(String[] args) throws IOException {
// 读文件
String file = "E:/pic.jpg";
String outFile = "E:/picunzip.jpg";
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
byte[] bytes1 = new byte[bufferedInputStream.available()];
bufferedInputStream.read(bytes1);
bufferedInputStream.close();
System.out.println("压缩前大小: " + bytes1.length);
// 压缩
byte[] bytes2 = ZipUtil.zip(bytes1);
System.out.println("压缩后大小: " + bytes2.length);
// 解压
byte[] bytes3 = ZipUtil.unzip(bytes2);
System.out.println("unzip解压后大小: " + bytes3.length);</span><span style="color: #008000">//</span><span style="color: #008000"> 输出到文件以便验证</span> BufferedOutputStream bufferedOutputStream = <span style="color: #0000ff">new</span> BufferedOutputStream(<span style="color: #0000ff">new</span><span style="color: #000000"> FileOutputStream(outFile)); bufferedOutputStream.write(bytes3); bufferedOutputStream.close();
}
}