JDK 自带压缩解压流

时间:2022-10-27 19:16:34

代码如下

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();

byte[] buffer = new byte[4096];
int i=0;
while ((i = zipInputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer,
0,i);
}
return byteArrayOutputStream.toByteArray();
}
return null;
}

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);

// 输出到文件以便验证
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(outFile));
bufferedOutputStream.write(bytes3);
bufferedOutputStream.close();
}
}