java将多个文件一起打成zip包后下载实例

//文件打包下载
    public static HttpServletResponse downLoadFiles(List<File> files,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            /**这个集合就是你想要打包的所有文件,
             * 这里假设已经准备好了所要打包的文件*/
            //List<File> files = new ArrayList<File>();
     
            /**创建一个临时压缩文件,
             * 我们会把文件流全部注入到这个文件中
             * 这里的文件你可以自定义是.rar还是.zip*/
            File file = new File("c:/certpics.rar");
            if (!file.exists()){   
                file.createNewFile();   
            }
            response.reset();
            //response.getWriter()
            //创建文件输出流
            FileOutputStream fous = new FileOutputStream(file);   
            /**打包的方法我们会用到ZipOutputStream这样一个输出流,
             * 所以这里我们把输出流转换一下*/
           ZipOutputStream zipOut 
            = new ZipOutputStream(fous);
            /**这个方法接受的就是一个所要打包文件的集合,
             * 还有一个ZipOutputStream*/
           zipFile(files, zipOut);
            zipOut.close();
            fous.close();
           return downloadZip(file,response);
        }catch (Exception e) {
                e.printStackTrace();
            }
            /**直到文件的打包已经成功了,
             * 文件的打包过程被我封装在FileUtil.zipFile这个静态方法中,
             * 稍后会呈现出来,接下来的就是往客户端写数据了*/
           
     
        return response ;
    }

  /**
     * 把接受的全部文件打成压缩包 
     * @param List<File>;  
     * @param org.apache.tools.zip.ZipOutputStream  
     */
    public static void zipFile
            (List files,ZipOutputStream outputStream) {
        int size = files.size();
        for(int i = 0; i < size; i++) {
            File file = (File) files.get(i);
            zipFile(file, outputStream);
        }
    }

    public static HttpServletResponse downloadZip(File file,HttpServletResponse response) {
        try {
        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();

        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");

//如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
        response.setHeader("Content-Disposition", "attachment;filename=" +URLEncoder.encode(file.getName(), "UTF-8"));
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        } catch (IOException ex) {
        ex.printStackTrace();
        }finally{
             try {
                    File f = new File(file.getPath());
                    f.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
        }
        return response;
    }

/**  
     * 根据输入的文件与输出流对文件进行打包
     * @param File
     * @param org.apache.tools.zip.ZipOutputStream
     */
    public static void zipFile(File inputFile,
            ZipOutputStream ouputStream) {
        try {
            if(inputFile.exists()) {
                /**如果是目录的话这里是不采取操作的,
                 * 至于目录的打包正在研究中*/
                if (inputFile.isFile()) {
                    FileInputStream IN = new FileInputStream(inputFile);
                    BufferedInputStream bins = new BufferedInputStream(IN, 512);
                    //org.apache.tools.zip.ZipEntry
                    ZipEntry entry = new ZipEntry(inputFile.getName());
                    ouputStream.putNextEntry(entry);
                    // 向压缩文件中输出数据   
                    int nNumber;
                    byte[] buffer = new byte[512];
                    while ((nNumber = bins.read(buffer)) != -1) {
                        ouputStream.write(buffer, 0, nNumber);
                    }
                    // 关闭创建的流对象   
                    bins.close();
                    IN.close();
                } else {
                    try {
                        File[] files = inputFile.listFiles();
                        for (int i = 0; i < files.length; i++) {
                            zipFile(files[i], ouputStream);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中可以使用`java.util.zip`来实现根据URL将多个文件zip并进行下载的功能。下面是一个示例代码: ```java import java.io.*; import java.net.URL; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class FileZipDownloader { public static void main(String[] args) { String zipUrl = "http://example.com/files.zip"; String[] fileUrls = {"http://example.com/file1.txt", "http://example.com/file2.txt"}; try { // 创建ZipOutputStream FileOutputStream fos = new FileOutputStream("downloaded_files.zip"); ZipOutputStream zos = new ZipOutputStream(fos); // 从URL下载并添加文件zip中 for (String fileUrl : fileUrls) { URL url = new URL(fileUrl); InputStream is = url.openStream(); zos.putNextEntry(new ZipEntry(url.getFile())); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { zos.write(buffer, 0, length); } is.close(); zos.closeEntry(); } // 关闭流 zos.close(); fos.close(); // 下载zip文件 downloadZip(zipUrl); } catch (IOException e) { e.printStackTrace(); } } private static void downloadZip(String url) throws IOException { URL zipUrl = new URL(url); InputStream is = zipUrl.openStream(); FileOutputStream fos = new FileOutputStream("downloaded_files.zip"); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { fos.write(buffer, 0, length); } is.close(); fos.close(); } } ``` 上述代码首先创建了一个`ZipOutputStream`对象,然后依次遍历多个文件的URL,将每个文件下载后添加到zip中,并关闭流。最后调用`downloadZip`方法根据zip文件的URL进行下载。请确保提供的URL和文件格式的可用性和正确性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值