解析zip文件-不生成临时文件的办法


package com.test;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;


public class ReadData {
public static void main(String args[])throws Exception{
File f = new File("/home/upload/TwitterBig.zip");
InputStream in = new FileInputStream(f);
byte bytes[]=new byte[(int)f.length()]; //创建合适文件大小的数组
in.read(bytes); //读取文件中的内容到b[]数组
in.close();

ByteArrayInputStream fis = new ByteArrayInputStream(bytes);
ZipInputStream zis = new ZipInputStream(fis);

ZipEntry ze = null;

while((ze = zis.getNextEntry()) != null){
String name = ze.getName();
System.out.println("File name****"+ze.getName());

long size = ze.getSize();

byte[] binary = readZipEntry(zis,size);
writeFile(binary,"/home/upload/parese/"+ze.getName());
}


}

private static byte[] readZipEntry(ZipInputStream zipIn, long size)
throws Exception {
ByteArrayOutputStream output = new ByteArrayOutputStream();
int oneByte = -1;
long offset = 0L;

try {
while ((oneByte = zipIn.read()) > -1) {
output.write((byte) oneByte);
offset++;
if (offset == size) {
break;
}
}
} finally {
output.close();
}
return output.toByteArray();
}

private static void writeFile(byte[] content, String filename) throws IOException {

File file = new File(filename);

if (!file.exists()) {
file.createNewFile();
}

FileOutputStream fop = new FileOutputStream(file);
BufferedOutputStream buff = new BufferedOutputStream(fop);

buff.write(content);
buff.flush();
buff.close();
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值