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即可解决。

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

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

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • js 判断是否字符串_js字符串查找

    js 判断是否字符串_js字符串查找整理js中可以用到的判断一个字符串中是否包含另外一个字符的方法String对象方法1、indexOfindexOf返回指定字符串在该字符中首次出现的位置,如果没有找到,则返回-1indexOf接收两个参数,第一是需要搜索的字符串,第二个参数是检索的位置,默认为0letstr=’abcde’;//例如,从str第三位开始搜索’a’console.log(str.indexOf(‘a’,2));//-1console.log(str.indexOf(‘a’))//02、

  • Python生成exe可执行文件

    Python生成exe可执行文件将Python文件编译成exe可执行文件,可使用pyinstaller工具或py2exe工具实现。这里使用pyinstaller来说明。安装pyinstaller模块使用pip安装pipinstallpyinstaller生成exe文件准备好需要编译成exe的Python文件在这个Python文件的当前路径执行pyinstaller-Fxxx.py(xxx为要Python…

  • 基金指数温度怎么看_指数温度是什么意思

    基金指数温度怎么看_指数温度是什么意思指数基金真的有那么好吗,连巴菲特也给家族制定自己死后把大部分资金都购买指数基金,如何挑选指数基金呢,有许多人推荐指数温度,那么基金指数温度靠谱吗,银行存款利率网小编和大家学习下指数温度查询技巧。基金指数温度靠谱吗指数温度是正态分布值,即当前估值在历史数值的位置占比,指数温度本质上就是以历史预测未来。关于基金指数温度靠谱吗,当然是有一定的参考价值,但也不能完全依靠关于基金指数温度来决定购买。下面我们…

    2022年10月23日
  • xps 转 pdf android版,xps文件转换pdf

    xps 转 pdf android版,xps文件转换pdfXPS阅读器是一款专门为XPS格式的文件而打造的阅读器,能够帮助用户在这款软件中对XPS文件一键阅读,并且能够随时打开。对于不知道用什么打开xps文件的朋友可以下载这款专用阅读器,它还能对xps文件进行格式转换。软件功能1、使用xpsviewer,你可以创建他人无法篡改而且打印效果始终与屏幕显示保持一致的电子文档与他人共享。典型的例子包括合同、备忘录、简历、新闻稿和报表。2、XML页面规范(…

  • laravel获取当前认证用户登录

    laravel获取当前认证用户登录

  • 单模和多模光纤可以混用吗_多模光纤和单模光纤能混用吗

    单模和多模光纤可以混用吗_多模光纤和单模光纤能混用吗我们知道光纤和光模块都有单模和多模两种类型,那么我们可能在使用中会产生疑问,单模/多模光纤和单模/多模光模块如何配套使用?它们可以混用吗?下面飞速光纤将通过问答的方式来为大家解答这个疑惑。  问:单模光纤和多模光纤有什么区别?  答:单模光纤采用固体激光器做光源;多模光纤则采用发光二极管做光源;单模光纤传输频带宽、传输距离长,但因其需要激光源,成本较高;多模光纤传输速度低、距离短,但其成本比较低;单模光纤芯径和色散小,仅允许一种模式传输;多模光纤芯径和色散大,允许上百种模式传输。  问:单模光模块和多模

发表回复

您的电子邮箱地址不会被公开。

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