java 流压缩_java压缩多个文件并且返回流示例

/**

* 方法描述:测试类

*/

public class TestFileStream{

//文件和压缩包存储的位置

StringtempFilePath="C:/temp/"

ListfileList=newArrayList();

fileList.add(tempFilePath+"file1.txt");

fileList.add(tempFilePath+"file2.png");

fileList.add(tempFilePath+"file3.xls");

//生成的压缩包名称

StringzipName="fileData";

//返回流

ByteArrayOutputStreamoutputStream=fileToZip(fileList,fileData,tempFilePath);

//页面输入压缩包流

byte[]buffer=outputStream.toByteArray();

//清空response

response.reset();

//设置response的Header

response.addHeader("Content-Disposition",

"attachment;filename="+

newString(("dataFile.zip").getBytes("gb2312"),"ISO8859-1"));

response.addHeader("Content-Length",""+outputStream.size());

toClient=newBufferedOutputStream(response.getOutputStream());

response.setContentType("application/octet-stream");

toClient.write(buffer);

toClient.flush();

}

/**

*方法描述:将多个文件压缩成zip包

*/

publicByteArrayOutputStreamfileToZip(ListfileList,StringzipName,StringtempFilePath){

byte[]buffer=newbyte[1024];

ZipOutputStreamout=null;

try{

out=newZipOutputStream(newFileOutputStream(tempFilePath+zipName+".zip"));

Listfiledata=newArrayList();

for(inti=0,len=fileList.size();i

{

filedata.add(newFile(fileList.get(i)));

}

for(intj=0,len=filedata.size();j

{

FileInputStreamfis=newFileInputStream(filedata.get(j));

out.putNextEntry(newZipEntry(filedata.get(j).getName()));

intdataLen;

//读入需要下载的文件的内容,打包到zip文件

while((dataLen=fis.read(buffer))>0){

out.write(buffer,0,dataLen);

}

out.closeEntry();

fis.close();

}

out.close();

}

catch(Exceptionex)

{

ex.printStackTrace();

}

//读取压缩包

Filefilezip=newFile(tempFilePath+zipName+".zip");

ByteArrayOutputStreambaos=null;

try

{

baos=newByteArrayOutputStream();

FileInputStreaminStream=newFileInputStream(filezip);

BufferedInputStreambis=newBufferedInputStream(inStream);

intc=bis.read();

while(c!=-1){

baos.write(c);

c=bis.read();

}

bis.close();

inStream.close();

}

catch(Exceptionex)

{

ex.printStackTrace();

}

returnbaos;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值