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

/**
    * 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. android在代码中四种设置控件(以及TextView的文字颜色)背景颜色的方法

      http://blog.csdn.net/fth826595345/article/details/9208771 主题 TextView 转载请注明出处: http://blog.csdn.ne ...

  2. Codeforces Round #337 (Div. 2) D. Vika and Segments 线段树 矩阵面积并

    D. Vika and Segments     Vika has an infinite sheet of squared paper. Initially all squares are whit ...

  3. Build better apps: Windows 10 by 10 development series

    http://blogs.windows.com/buildingapps/2015/08/05/build-better-apps-windows-10-by-10-development-seri ...

  4. Codeforces Alpha Round #20 (Codeforces format) C. Dijkstra?(裸的dijkstra)

    题目链接:http://codeforces.com/problemset/problem/20/C 思路:需要用优化过的dijkstra,提供两种写法. #include <iostream& ...

  5. loj 1099(最短路)

    题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=25956 思路:dist[v][0]代表走到点v的最短路,dist[ ...

  6. Xcode 缓存 帮助文档 隐藏文件夹显示方法

    删除Xcode的缓存路径是:/Users/用户名/Library/Developer/Xcode/DerivedData(默认情况下, 这是一个隐藏文件夹) 显示隐藏文件夹 指令如下:显示隐藏文件: ...

  7. whl文件安装

    进入whl文件的目录,直接pip install ...即可

  8. 【SSH】 之 Struts2环境搭建及简单应用开发

    在上一篇文章中,我们一起了解了一下struts2的工作机制原理,接下来让我们进行一下简单应用的开发 (一)配置环境 1.建立web项目 2.导入jar包 其中struts2中有很多jar包,我们不需要 ...

  9. 计数排序-java

    今天看了一本书,书里有道题,题目很常见,排序,明了点说: 需求:输入:最多有n个正整数,每个数都小于n, n为107 ,没有重复的整数 输出:按升序排列 思路:假设有一组集合 {1,3,5,6,11, ...

  10. Smart原则

    遵循smart原则,必须是具体的.可衡量的.可达到的.与岗位职责相关的.有明确达成期限的.