加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:36:30 所属栏目:Java 来源:网络整理
导读:这个类可以压缩多个文件并且返回流,在程序中可以再操作返回的流做其它功能,比如验证MD5,下面看代码吧 复制代码 代码如下: /** * 方法描述:b测试类/b/br */ public class TestFileStream{ //文件和压缩包存储的位置 StringtempFilePath="C:/temp/" ListSt

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

您可能感兴趣的文章:

  • java实现文件压缩成zip的工具类
  • java压缩zip文件中文乱码问题解决方法
  • java实现文件上传下载和图片压缩代码示例
  • java使用gzip实现文件解压缩示例
  • 实例展示使用Java压缩和解压缩7z文件的方法
  • java生成压缩文件示例代码
  • Java实现多文件压缩打包的方法
  • 使用Java生成jpg与压缩图片为jpg文件的代码示例
  • Java创建ZIP压缩文件的方法
  • java实现多个文件压缩成压缩包

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读