//下载单个文件调用方法

/**
    * response
    * imgPath 下载图片地址
    * fileName 保存下载文件名称
    * @date 2015年4月14日 下午5:53:24
    */
    public static void download(HttpServletResponse response,String imgPath,String fileName){
         OutputStream out=null;
         BufferedInputStream br =null;
         try {
                // 设置响应类型为下载
                 response.setContentType("application/x-msdownload;charset=UTF-8");
                 //页面乱码问题
                response.setCharacterEncoding("UTF-8");
                //设置下载文件名称
                response.setHeader("Content-Disposition", "attachment; filename="+fileName);
                //输入流
                br = new BufferedInputStream(new FileInputStream(imgPath));
                byte[] buf = new byte[1024];
                int len = 0;
                out = response.getOutputStream();
                while ((len = br.read(buf)) > 0){
                      out.write(buf, 0, len);
                      out.flush();
                }
                if(null!=out) out.close();
                if(null!=br) br.close();
         } catch (Exception e) {
               e.printStackTrace();
         }
    }

//下载打包压缩文件调用方法

/**
     *files 需要下载问价的File 集合
    * @Description: TODO(文件打包下载)
    */
    public static HttpServletResponse downLoadFiles(List<File> files,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            ServletContext context=request.getSession().getServletContext();
            /**这个集合就是你想要打包的所有文件,
             * 这里假设已经准备好了所要打包的文件*/
            //List<File> files = new ArrayList<File>();
    
            /**创建一个临时压缩文件,
             * 我们会把文件流全部注入到这个文件中
             * 这里的文件你可以自定义是.rar还是.zip*/

File file = new File(context.getRealPath("/test.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();
            }
        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");
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        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[1024];
                    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();
        }
    }

JAVA代码实现下载单个文件,和下载打包文件的更多相关文章

  1. java代码和spring框架读取xml和properties文件

    1.java文件读取properties文件 Properties props = new Properties(); try { //资源文件存放在类文件的根目录下.即是放在src下面.则不需要写路 ...

  2. java代码判断图片文件格式, 不是根据文件后缀来判断。

    public static final String TYPE_JPG = "jpg"; public static final String TYPE_GIF = "g ...

  3. Linux正则表达式、shell基础、文件查找及打包压缩

    Linux正则表达式.shell基础.文件查找及打包压缩 一.正则表达式 Linux正则表达式分为2类: 1.基本正则表达式(BRE) 2.扩展正则表达式(ERE) 两者的区别: 1.使用扩展正则表达 ...

  4. Linux_打包文件

    将多个文件打包成一个大文件,用tar命令 tar是将多个文件前后连接在一起,tar并不对文件进行压缩 tar -cf  要创建的打包文件名(最后加上.tar)  要打包的文件/列表      c代表创 ...

  5. 用java 代码下载Samba服务器上的文件到本地目录以及上传本地文件到Samba服务器

    引入: 在我们昨天架设好了Samba服务器上并且创建了一个 Samba 账户后,我们就迫不及待的想用JAVA去操作Samba服务器了,我们找到了一个框架叫 jcifs,可以高效的完成我们工作. 实践: ...

  6. java代码实现ftp服务器的文件上传和下载

    java代码实现文件上传到ftp服务器: 1:ftp服务器安装: 2:ftp服务器的配置: 启动成功: 2:客户端:代码实现文件的上传与下载: 1:依赖jar包: 2:sftpTools   工具类: ...

  7. JAVA代码时间SFTP文件的下载

    参考文章:http://blog.csdn.net/smallerpig/article/details/50976191 SFTP文件的下载与FTP文件的下载差别较大,需要下载jsch-0.1.54 ...

  8. 【Azure Developer】VS Code运行Java 版Azure Storage SDK操作Blob (新建Container, 上传Blob文件,下载及清理)

    问题描述 是否可以用Java代码来管理Azure blob? 可以.在代码中加入azure-storage-blob依赖.即可使用以下类操作Azure Storage Blob. BlobServic ...

  9. Java ftp 上传文件和下载文件

    今天同事问我一个ftp 上传文件和下载文件功能应该怎么做,当时有点懵逼,毕竟我也是第一次,然后装了个逼,在网上找了一段代码发给同事,叫他调试一下.结果悲剧了,运行不通过.(装逼失败) 我找的文章链接: ...

随机推荐

  1. 用C获得当前系统时间(转)

    #include <stdio.h> #include <time.h> void main () { time_t rawtime; struct tm * timeinfo ...

  2. 在Salesforce中通过dataloadercliq调用data loader来批量处理数据

    上一篇文章讲到,通过data loader去批量处理数据,那么这篇文章将主要讲解在Salesforce中通过dataloadercliq调用data loader来批量处理数据. 1): CLIq文件 ...

  3. suse 不能远程登录

    公司部分机器新装了suse企业版12,远程登录不成功,解决方法如下: 1.关闭防火墙 chkconfig --level SuSEfirewall2_init off 2.配置sshd 3.重启ssh ...

  4. 纯window下VMware 安装 OS X El Capitan 原版映像【未完待续】

    一.所需软件1.下载OS X El Capitan 10.11.2 15C50链接:http://pan.baidu.com/s/1skuLgAx 密码:u2jf 2.下载VMware Worksta ...

  5. JavaScript内置对象(字符串,数组,日期的处理)

    Date 日期对象 日期对象可以储存任意一个日期,并且可以精确到毫秒数(1/1000 秒). 定义一个时间对象 : var Udate=new Date(); 注意:使用关键字new,Date()的首 ...

  6. XSS 跨站脚本攻击之ShellCode的调用

    1.ShellCode,最初是溢出程序和蠕虫病毒的核心,实际上是指利用一个漏洞是所执行的代码,在XSS跨站脚本中,是指由javascript等脚本编写的XSS利用代码: 2.Exploit,在黑客眼里 ...

  7. POJ 1743 后缀数组

    题目链接:http://poj.org/problem?id=1743 题意:给定一个钢琴的音普序列[值的范围是(1~88)],现在要求找到一个子序列满足 1,长度至少为5 2,序列可以转调,即存在两 ...

  8. 移动网页 -- CSS布局

    1.多栏结构 column-count column-width column:120px 3: column-gap:2em: column-rule:2px dotted gray: 跨越以及打断 ...

  9. unity mathf.repeat 截取操作

    截取操作,可用于浮点数. Mathf.Repeat(Time.realtimeSinceStartup, 3*blinkTime) > blinkTime;

  10. [转] linux 下查看一个进程运行路径的方法

    http://blog.csdn.net/brioxu/article/details/5104736 在linux下查看进程大家都会想到用 ps -ef|grep XXX ps -aux | hea ...