发布于 2016-07-11 07:23:22 | 197 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Java函数式编程,程序狗速度看过来!

Java程序设计语言

java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台(即JavaEE(j2ee), JavaME(j2me), JavaSE(j2se))的总称。


这篇文章主要介绍了java压缩多个文件并且返回流示例,返回压缩流主是为了在程序里再做其它操作,需要的朋友可以参考下

这个类可以压缩多个文件并且返回流,在程序中可以再操作返回的流做其它功能,比如验证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;
}



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务