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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • golang激活码2021(JetBrains全家桶)

    (golang激活码2021)这是一篇idea技术相关文章,由全栈君为大家提供,主要知识点是关于2021JetBrains全家桶永久激活码的内容https://javaforall.net/100143.htmlIntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,上面是详细链接哦~0UY7RF7AC5-eyJsaWNlb…

    2022年3月28日
    154
  • Try out the latest C++ compiler toolset without waiting for the next update of Visual Studio

    Updated22/Apr/2016:TheNuGet packageis nowbeinguploadeddaily.Thepayloaddoesn’tch

    2021年12月23日
    38
  • isnotempty和isnotnull_was not iterable

    isnotempty和isnotnull_was not iterable先看看isEmpty和isBlank  从效果来看,当a=””,字符中有空格时,IsEmpty是算他不为空的本质上讲:isEmpty等价于str==null||str.length==0isBlank等价于str==null||str.length==0||str.trim().length==0我们再来看非空:is…

    2022年10月7日
    0
  • Spring笔记(4)

    Spring笔记(4)

    2021年11月11日
    45
  • 基于知识图谱的知识推理

    基于知识图谱的知识推理这基于知识图谱的知识推理基本概念、定义推理方法分为三类:知识图推理的相关应用基于规则的推理基于表示学习的推理基于神经网络和强化学习的推理基本概念、定义人工智能算法必须具有推理能力,推理过程必须依赖于知识工程时代的先验知识和经验,大量知识图(KGs),如YAGO(Suchanek,Kasnki,2008),WordNet(Miller,1995),Freebase(Bollacker,Evans、Paritosh、Sturge和Taylor,2008)已经开发。KGs包含大量的先验知识,同时也能有效地组织

    2022年6月11日
    65
  • 码流 / 码率 / 比特率 / 帧速率 / 分辨率的区别[通俗易懂]

    码流 / 码率 / 比特率 / 帧速率 / 分辨率的区别[通俗易懂]码流/码率/比特率/帧速率/分辨率/高清的区别2015年03月13日10:40:30阅读数:143980GOP/ 码流/码率/比特率/帧速率/分辨率 GOP(Groupofpicture)      关键帧的周期,也就是两个IDR帧之间的距离,一个帧组的最大帧数,一般而言,每一秒视频至少需要使用1个关键帧。增加关键帧个数可…

    2022年5月28日
    70

发表回复

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

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