java byte 解压_【Java基础】JDK 自带压缩解压流

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

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值