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

/**
    * 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. 4.0 和4.5 app 和generic,xaml的问题

    4.0里面不支持Generic.xaml里面 <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source=& ...

  2. 实现Web验证码图片-原理

    实现验证码的基础 GDI+ graphics device interface plus的缩写,即图形设备接口.GDI+为开发者提供了一组实现与各种设备(具有图形化能力但不涉及图形细节的设备)进行交互 ...

  3. 廖雪峰js教程笔记6 generator一个坑 看完python在回来填坑

    generator(生成器)是ES6标准引入的新的数据类型.一个generator看上去像一个函数,但可以返回多次. ES6定义generator标准的哥们借鉴了Python的generator的概念 ...

  4. css整理-05 边框,背景和浮动,定位

    边框 样式:border-style hidden, dotted, dashed, solid , double, groove, ridge, inset, outset 最不可预测的是doubl ...

  5. Android实现全屏的三种方式

    一.通过代码 requestWindowFeature(Window.FEATURE_NO_TITLE);// 隐藏标题栏 getWindow().setFlags(WindowManager.Lay ...

  6. spring mvc 注解访问控制器以及接收form数据的方式,包括直接接收日期类型及对象的方法

    Spring 中配置扫描器 <!-- springmvc的扫描器--> <context:component-scan base-package="com.beifeng. ...

  7. C# 词法分析器(三)正则表达式

    系列导航 (一)词法分析介绍 (二)输入缓冲和代码定位 (三)正则表达式 (四)构造 NFA (五)转换 DFA (六)构造词法分析器 (七)总结 正则表达式是一种描述词素的重要表示方法.虽然正则表达 ...

  8. 【原】iOS多线程之NSThread、NSOperationQueue、NSObject和GCD的区别

    区别: Thread: 是这几种方式里面相对轻量级的,但也是使用起来最负责的,你需要自己管理thread的生命周期,线程之间的同步.线程共享同一应用程序的部分内存空间, 它们拥有对数据相同的访问权限. ...

  9. sed 格式化输出df -h

    df -h|sed '1d;/ /!N;s/\n//;s/ \+/ /;' 1d——————删除第一行 / /!N——————没有空格的行执行N 例子中没有空格的行 /dev/mapper/vg_ds ...

  10. 2076. The Drunk Jailer

    Problem A certain prison contains a long hall of n cells, each right next to each other. Each cell h ...