zip压缩流转本地文件及解压

有一个需求,HTTP获取到zip文件的byte数组,需要转为本地的zip或是解压zip文件。


1. 用到的class

import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import java.io.ByteArrayInputStream;

2 获取解压后的文件

private static void getTxtFile(byte[] data) throws Exception {
		ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(data));
		ZipEntry entry = null;
		while ((entry = zipStream.getNextEntry()) != null) {

			String entryName = entry.getName();

			FileOutputStream out = new FileOutputStream("/log/111/" + entryName);

			byte[] byteBuff = new byte[4096];
			int bytesRead = 0;
			while ((bytesRead = zipStream.read(byteBuff)) != -1) {
				out.write(byteBuff, 0, bytesRead);
			}

			out.close();
			zipStream.closeEntry();
		}
		zipStream.close();
}

3. 转存zip文件,(可修改zip内的文件名)

private static void getZipFile(byte[] data) throws Exception {
		String filename = "/log/111/111.zip";
		FileOutputStream fileOutputStream = new FileOutputStream(filename);
		ZipOutputStream zos = new ZipOutputStream(fileOutputStream);

		ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(data));
		ZipEntry entry;
		while ((entry = zipStream.getNextEntry()) != null) {
			ZipEntry entry1 = new ZipEntry(entry.getName());
			zos.putNextEntry(entry1);
			zipStream.closeEntry();
		}
		zos.write(data);
		zos.flush();
		zos.closeEntry();
		zos.close();
		zipStream.close();
}

或者简单粗暴的直接将其保存到本地文件

private static void getZipFile(byte[] data) throws Exception {
		String filename = "/log/111/111.zip";
		File targetFile = new File(filename);
		OutputStream outStream = new FileOutputStream(targetFile);
		outStream.write(data);
		outStream.flush();
		outStream.close();
}


 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值