java下载文件或文件夹

java下载文件或文件夹最近接到一个需求,就是将远程目录下的文件或文件夹下载到指定目录下,下面来看下最后的成果。1.首先,IO流输出文件(可以在浏览器端下载)publicHttpServletResponsedownload(StringfileName,HttpServletResponseresponse){Filefile=newFile(gitConfig.getDestPath()+”/”+fileName);if(file.isDirec

大家好,又见面了,我是你们的朋友全栈君。

最近接到一个需求,就是将远程目录下的文件或文件夹下载到指定目录下,下面来看下最后的成果。

1.首先,IO流输出文件(可以在浏览器端下载)

   public HttpServletResponse download(String fileName, HttpServletResponse response) {
        File file = new File(gitConfig.getDestPath() + "/" + fileName);
        if (file.isDirectory()){
            return downDestroy(file, response);
        }else{
            return downFile(file,response);
        }

    }

    /**
     * 下载文件
     * @param file
     * @param response
     * @return
     */
    private HttpServletResponse downFile(File file, HttpServletResponse response) {
        InputStream fis = null;
        OutputStream toClient = null;
        try {
            // 以流的形式下载文件。
            fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            // 清空response
            response.reset();
            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();
        } catch (IOException ex) {
            ex.printStackTrace();
        }finally{
            try {
                File f = new File(file.getPath());
                f.delete();
                if(fis!=null){
                    fis.close();
                }
                if(toClient!=null){
                    toClient.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    /**
     * 下载文件夹
     * @param file
     * @param response
     * @return
     */
    private HttpServletResponse downDestroy(File file, HttpServletResponse response) {
        String zipFilePath = gitConfig.getDestPath()+"/"+file.getName()+"_"+System.currentTimeMillis()/1000+".zip";
        ZipCompressor zipCompressor = new ZipCompressor(zipFilePath);
        try {
            zipCompressor.compress(file.getPath());
            File zipFile = new File(zipFilePath);
            downFile(zipFile,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

对应的工具类


import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 压缩类
 *
 */
public class ZipCompressor {

    static final int BUFFER = 8192;

    /**
     * 压缩的文件夹
     */
    private File zipFile;

    public ZipCompressor(String pathName) {
        zipFile = new File(pathName);
    }


    /**
     * 遍历需要压缩文件集合
     * @param pathName
     * @throws IOException
     */
    public void compress(String... pathName) throws IOException {
        ZipOutputStream out =null;
        FileOutputStream fileOutputStream=null;
        CheckedOutputStream cos=null;
        try {
            fileOutputStream = new FileOutputStream(zipFile);
            cos = new CheckedOutputStream(fileOutputStream,new CRC32());
            out = new ZipOutputStream(cos);
            String basedir = "";
            for (int i=0;i<pathName.length;i++){
                compress(new File(pathName[i]), out, basedir);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            if(out!=null){
                out.close();
            }
            if(fileOutputStream!=null){
                fileOutputStream.close();
            }
            if(cos!=null){
                cos.close();
            }
        }
    }
    /**
     * 压缩
     * @param file
     * @param out
     * @param basedir
     */
    private void compress(File file, ZipOutputStream out, String basedir) throws IOException {
        // 判断是目录还是文件
        if (file.isDirectory()) {
            this.compressDirectory(file, out, basedir);
        } else {
            this.compressFile(file, out, basedir);
        }
    }
    /**
     * 压缩一个目录
     * */
    private void compressDirectory(File dir, ZipOutputStream out, String basedir) throws IOException {
        if (!dir.exists()){
            return;
        }
        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 递归
            compress(files[i], out, basedir + dir.getName() + "/");
        }
    }
    /**
     * 压缩一个文件
     *
     * */
    private void compressFile(File file, ZipOutputStream out, String basedir) throws IOException {
        if (!file.exists()) {
            return;
        }
        BufferedInputStream bis =null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            ZipEntry entry = new ZipEntry(basedir + file.getName());
            out.putNextEntry(entry);
            int count;
            byte[] data = new byte[BUFFER];
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            if(bis!=null){
                bis.close();
            }
        }
    }
}

2.接收IO文件流,并保存到本地(文件夹类接收的是压缩文件,接收完之后会将压缩文件解压然后删除压缩文件)

    public void downFileOrDestroy(String fileName){
        boolean isfile = true;
        if (fileName.indexOf(".")==-1){
            //如果是文件夹
            isfile =false;
        }
        String pluginsDir = "D:/file";
        URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File path = new File(pluginsDir);
        if (!path.exists()){
            path.mkdirs();
        }
        File f = null;
        if (isfile){
            f = new File(pluginsDir+"/"+fileName);
        }else{
            f = new File(pluginsDir+File.separator+fileName+"_"+System.currentTimeMillis()/1000+".zip");
        }
        try {
            urlfile = new URL("文件IO输出接口地址?fileName="+fileName);
            httpUrl = (HttpURLConnection) urlfile.openConnection();
            httpUrl.connect();
            InputStream inputStream = httpUrl.getInputStream();
            bis = new BufferedInputStream(inputStream);
            FileOutputStream fileOutputStream = new FileOutputStream(f);
            bos = new BufferedOutputStream(fileOutputStream);
            int len = 2048;
            byte[] b = new byte[len];
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            bos.flush();
            bos.close();
            bis.close();
            httpUrl.disconnect();
            if (!isfile){
                //如果是文件夹,下载下来的是压缩文件,要解压文件
                ZipUtil.unZipUncompress(f.getPath(),pluginsDir);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

涉及到的工具类:

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * @Author cs
 * @Date 2020/12/31 11:51
 * @Version 1.0
 */
public class ZipUtil {

    /**
     * zip文件解压
     * @param inputFile  待解压文件夹/文件
     * @param destDirPath  解压路径
     */
    public static void unZipUncompress(String inputFile,String destDirPath){
        File srcFile = new File(inputFile);//获取当前压缩文件
        InputStream is = null;
        FileOutputStream fos = null;
        try{
            // 判断源文件是否存在
            if (!srcFile.exists()) {
                throw new Exception(srcFile.getPath() + "所指文件不存在");
            }
            ZipFile zipFile = new ZipFile(srcFile);//创建压缩文件对象
            //开始解压
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                // 如果是文件夹,就创建个文件夹
                if (entry.isDirectory()) {
                    srcFile.mkdirs();
                } else {
                    // 如果是文件,就先创建一个文件,然后用io流把内容copy过去
                    File targetFile = new File(destDirPath + "/" + entry.getName());
                    // 保证这个文件的父文件夹必须要存在
                    if (!targetFile.getParentFile().exists()) {
                        targetFile.getParentFile().mkdirs();
                    }
                    targetFile.createNewFile();
                    // 将压缩文件内容写入到这个文件中
                    is = zipFile.getInputStream(entry);
                    fos = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[1024];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    // 关流顺序,先打开的后关闭
                    fos.close();
                    is.close();
                }
            }
            zipFile.close();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //删除压缩文件
            boolean delete = srcFile.delete();
            System.out.println(delete);
        }
    }
}

有的朋友可能会遇到临时文件删除不掉的问题,一般出现这种情况的原因都是IO没关闭,检查下自己的代码,先打开的IO后关闭,按顺序关闭IO即可解决。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/156955.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • jvm可达性分析算法_对点网络

    jvm可达性分析算法_对点网络作者:张华发表于:2016-04-05版权声明:可以任意转载,转载时请务必以超链接形式标明文章原始出处和作者信息及本版权声明(http://blog.csdn.net/quqi99)IP层叫分片,TCP/UDP层叫分段。网卡能做的事(TCP/UDP组包校验和分段,IP添加包头校验与分片)尽量往网卡做,网卡不能做的也尽量迟后分片(发送)或提前合并片(接收)来减少在网络栈中传输和处理的包数目,

    2025年6月14日
    3
  • intellij idea和eclipse比较_eclipse与idea的区别

    intellij idea和eclipse比较_eclipse与idea的区别             【总结】IDEA和Eclipse的比较    两个开发编辑器,可以说Eclispe之前占据了上风,但近几年来IDEA的使用率猛扑直追,现在IDEA有着反超的气势,到底两者之间有什么相似之处,又有什么区别呢?我们来看一下~~。   一、快捷键比较快捷键 Eclipse IDEA 查找类名 CTRL+…

    2022年8月26日
    8
  • 低代码开发平台技术架构_一个项目的整体架构是什么

    低代码开发平台技术架构_一个项目的整体架构是什么介绍JAVA低代码快速开发平台的整体架构设计

    2022年8月23日
    6
  • 机器学习十大算法简介

    机器学习十大算法简介K-Means算法K-Means算法是一种聚类算法,把n个对象根据他们的属性分成k个分类,并且使这K个分割的内部相似度最大,而分割之间的相似度最小。其主要的算法流程如下:1.从n个对象中任意选K个对象,作为每个聚类的中心2.根据K个中心,按照每个对象离K个中心的最小距离(离那个中心近,就划分到哪个中心),将n个对象划分成K个分割(聚类)3.然后计a ge su a分割的中心(

    2025年5月28日
    3
  • vue.js单页应用_vue嵌入第三方页面

    vue.js单页应用_vue嵌入第三方页面今天我们看看VUE怎么开发单页面应用,VUE提供了脚手架vue-cli,通过这个可以很轻松的创建VUE单页面应用,1.创建VUE项目  首先确保电脑上安装了NODE.JS, 在创建项目的目录下,打开CMD命令行,执行脚手架命令,安装脚手架cli. #全局安装vue-cli,一定要在全局模式下安装vue-cli,否则无法使用vue命令npminstall-gvue…

    2022年10月13日
    4
  • shell中的while循环实例[通俗易懂]

    shell中的while循环实例[通俗易懂]1.利用while循环计算1到100的和:示例代码1:#!/bin/bashi=1sum=0while[$i-le100]do letsum=sum+$i leti++doneecho$sum示例代码2:利用while循环计算1到100之间所有奇数之和#!/bin/bashi=1sum=0while[$i-le100]do letsum=sum+$i leti…

    2022年7月24日
    10

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号