您的位置:首页 > 其它

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

2016-01-07 15:55 381 查看
有一个需求,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();
}


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: