packagecom.test.java.zip;importjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.ByteArrayInputStream;importjava.io.ByteArrayOutputStream;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.util.zip.ZipEntry;importjava.util.zip.ZipInputStream;importjava.util.zip.ZipOutputStream;/***@authorjrwangxin1 字节数组压缩解压工具*/
public classZipUtil {/**压缩*/
public static byte[] zip(byte[] source) throwsIOException {
ByteArrayOutputStream byteArrayOutputStream= newByteArrayOutputStream();
ZipOutputStream zipOutputStream= newZipOutputStream(byteArrayOutputStream);
zipOutputStream.putNextEntry(new ZipEntry("0"));
BufferedOutputStream bufferedOutputStream= newBufferedOutputStream(zipOutputStream);
bufferedOutputStream.write(source);
bufferedOutputStream.close();returnbyteArrayOutputStream.toByteArray();
}/**解压*/
public static byte[] unzip(byte[] source) throwsIOException {
ZipInputStream zipInputStream= new ZipInputStream(newByteArrayInputStream(source));while (zipInputStream.getNextEntry() != null) {
ByteArrayOutputStream byteArrayOutputStream= newByteArrayOutputStream();byte[] buffer = new byte[4096];int i=0;while ((i = zipInputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer,0,i);
}returnbyteArrayOutputStream.toByteArray();
}return null;
}public static void main(String[] args) throwsIOException {//读文件
String file = "E:/pic.jpg";
String outFile= "E:/picunzip.jpg";
BufferedInputStream bufferedInputStream= new BufferedInputStream(newFileInputStream(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);//输出到文件以便验证
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(newFileOutputStream(outFile));
bufferedOutputStream.write(bytes3);
bufferedOutputStream.close();
}
}