当前位置: 移动技术网 > IT编程>开发语言>Java > java压缩多个文件并且返回流示例

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

这个类可以压缩多个文件并且返回流,在程序中可以再操作返回的流做其它功能,比如验证md5,下面看代码吧

复制代码 代码如下:

/**
* 方法描述:<b>测试类</b></br>
*/
public class testfilestream{
 //文件和压缩包存储的位置
stringtempfilepath="c:/temp/"
list<string>filelist=newarraylist<string>();
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();
}

/**
*方法描述:<b>将多个文件压缩成zip包</b></br>
*/
publicbytearrayoutputstreamfiletozip(list<string>filelist,stringzipname,stringtempfilepath){
byte[]buffer=newbyte[1024];
zipoutputstreamout=null;
try{
out=newzipoutputstream(newfileoutputstream(tempfilepath+zipname+".zip"));
list<file>filedata=newarraylist<file>();
for(inti=0,len=filelist.size();i<len;i++)
{
filedata.add(newfile(filelist.get(i)));
}

for(intj=0,len=filedata.size();j<len;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;
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网