国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java壓縮多個文件并且返回流示例

2019-11-26 15:36:33
字體:
來源:轉載
供稿:網友

這個類可以壓縮多個文件并且返回流,在程序中可以再操作返回的流做其它功能,比如驗證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;
}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 讷河市| 双流县| 临颍县| 卢氏县| 清水河县| 乾安县| 铁岭县| 塔城市| 石阡县| 井陉县| 嘉定区| 锦屏县| 南开区| 合川市| 多伦县| 香港| 英吉沙县| 棋牌| 故城县| 定州市| 宜兰市| 阜平县| 定日县| 华亭县| 曲水县| 沂南县| 阿克苏市| 株洲县| 宜宾市| 江华| 福州市| 平塘县| 嘉祥县| 苗栗市| 南澳县| 南京市| 梁平县| 乐东| 通城县| 马关县| 锦州市|