把多個文件壓縮成zip文件然後實現下載

在做下載功能時,遇到要同時下載多個文件的情況。試過多種方法,最好的一種就是把這些需要下載的文件,打包成壓縮文件,然後下載這個壓縮文件。

下面是實現的代碼:

package com.cbkcbp.businessreport.businessreport01;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;

public class Test {


/**
* @param args
* @throws IOException 
*/
public static void main(String[] args) throws IOException {
ZipOutputStream zipOut = null;
String zipUrl = "";
//response:是要通過提交表單來響應
HttpServletResponse response = null;
String zipName = "test.zip";
String attachment = "attachment";
byte[] buffer = new byte[1024]; 
//Zip文件產出的路徑
zipUrl = "c:test/test1.xls※c:test/test2.xls※c:test/test3.xls";
zipOut = new ZipOutputStream(new FileOutputStream(zipUrl));
//以"※"為分割符,截取報表Url(因為可能會有多份文件需要壓縮)
String [] attachUrls = zipUrl.split("※");
for(int i=0; i < attachUrls.length; i++){
//截取文件名,比如:"c:test/test.xls" 可截取得:"test.xls"
File tempFile =new File(attachUrls[i].trim());
//文件名
       String fileName = tempFile.getName();
FileInputStream fis = new FileInputStream(attachUrls[i].trim());
zipOut.putNextEntry(new ZipEntry(fileName));   
       int len;   
       //讀入需要下載文件的內容,打包到zip文件
       while((len = fis.read(buffer))>0) { 
        zipOut.write(buffer,0,len);    
       }   
       zipOut.closeEntry();   
       fis.close();
}
//讀取產出壓縮文件的字節流byte
byte [] reportByte = Test.toByteArray(zipUrl);
//將打包好的壓縮文件輸出Client端
Test.processWebOutput(reportByte, zipName, response, attachment);
}

/**
* 根據文件的路徑讀取文件的字節流byte
* @param fileName
* @return
* */
public static byte[] toByteArray(String fileName) throws IOException{ 
        File file = new File(fileName);  
        if(!file.exists()){  
            throw new FileNotFoundException(fileName);  
        } 
        ByteArrayOutputStream bos = new ByteArrayOutputStream((int)file.length());  
        BufferedInputStream bis = null;  
        try{  
        bis = new BufferedInputStream(new FileInputStream(file));  
            int buf_size = 1024;  
            byte[] buffer = new byte[buf_size];  
            int len = 0;  
            while(-1 != (len = bis.read(buffer,0,buf_size))){  
                bos.write(buffer,0,len);  
            }  
            return bos.toByteArray();  
        }catch (IOException e) {  
            e.printStackTrace();  
            throw e;  
        }finally{  
            try{  
            bis.close();  
            }catch (IOException e) {  
                e.printStackTrace();  
            }  
            bos.close();  
        }  


/**
* 將打包好的壓縮文件輸出在Client端
* @param bytes
* @param fileName
* @param response
* @param attachment
* @throws Exception
*/
public static void processWebOutput(byte[] bytes, String fileName
, HttpServletResponse response, String attachment){
OutputStream ouputStream = null;
try{
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition",attachment +" ; filename=" + fileName);
ouputStream = response.getOutputStream();
ouputStream.write(bytes);

}catch(Exception e){
e.printStackTrace();
}finally{
try{
ouputStream.flush();
ouputStream.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以使用java.util.zip包下的相关类来实现将文件压缩成zip文件的功能。以下是一个简单的示例代码: ```java import java.io.*; import java.util.zip.*; public class ZipUtils { public static void compressFileToZip(String sourceFilePath, String zipFilePath) { try { // 创建压缩文件输出流 FileOutputStream fos = new FileOutputStream(zipFilePath); ZipOutputStream zos = new ZipOutputStream(fos); // 创建待压缩的文件输入流 FileInputStream fis = new FileInputStream(sourceFilePath); BufferedInputStream bis = new BufferedInputStream(fis); // 往压缩包中写入文件 zos.putNextEntry(new ZipEntry(sourceFilePath)); byte[] buffer = new byte[1024]; int len; while ((len = bis.read(buffer)) > 0) { zos.write(buffer, 0, len); } // 关闭输入输出流 bis.close(); fis.close(); zos.closeEntry(); zos.close(); System.out.println("文件压缩成功!"); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { String sourceFilePath = "source.txt"; // 待压缩的文件路径 String zipFilePath = "compressed.zip"; // 压缩后的zip文件路径 compressFileToZip(sourceFilePath, zipFilePath); } } ``` 以上代码中,我们首先创建一个压缩文件输出流(`ZipOutputStream`),并指定输出文件路径。然后创建一个待压缩的文件输入流(`FileInputStream`)和一个缓冲输入流(`BufferedInputStream`)。接下来,我们将待压缩的文件写入压缩包(`zip` 文件)中,并使用缓冲区逐块写入。最后,关闭输入输出流,完成文件的压缩操作。 注意:上述代码只能压缩一个文件,如果要压缩多个文件,需要在循环中依次压缩每一个文件。另外,压缩完成后,可以通过解压缩操作还原被压缩的文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值