Java实现批量下载文件

   //action

 public String exportFile1() {
        // TODO Auto-generated method stub
        HttpServletResponse response= ServletActionContext.getResponse();
        HttpServletRequest request = ServletActionContext.getRequest();
        String id = request.getParameter("id");
        String filename = request.getParameter("filename");
        String[] idArr = id.split(",");
        String[] filenameArr = filename.split(",");
        System.out.println(id+"-----"+ filename.replace(" ", ""));
        String filePath = Configration.getApplicationRootPath()+Configration.getProperty("file_PATH") + File.separator+"fileuplod";
        // windows
//        String zipPath = filePath+ "\\"+"zipdata.zip";
        //linux
        String zipPath = filePath+ "//"+"zipdata.zip";
        
        String fileString = "";
        File[] srcfile = new File[idArr.length];
        for(int i = 0;i < idArr.length;i++){
           fileString = specialLineDao.exportFile1(idArr[i]);
           try {
               FileExpUtils.createMkdir(filePath);
               // windows
//               String filePath1 = filePath + "\\"+filenameArr[i];
               //linux
               String filePath1 = filePath + "//"+filenameArr[i];
//               FileExpUtils.createFile(filePath, FileByteUtil.getFromBASE64ToByte(fileString));
               File file = new File(filePath1);
                if (!file.exists()) {
                    file.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(FileByteUtil.getFromBASE64ToByte(fileString));
                fos.flush();
                fos.close();
                srcfile[i]=file;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }
        //创建压缩文件
        File file1 = new File(zipPath);
        if (!file1.exists()) {
            try {
                file1.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //将文件压缩
        zipFiles(srcfile,file1);
        //下载打包的压缩包
        downloadZip(file1,response); 
        //删除目录及目录下的文件
        FileExpUtils.deleteDirectory(filePath);
        return null;
    }
    public static void zipFiles(File[] srcfile,File zipfile){
        byte[] buf=new byte[1024];
        try {
            //ZipOutputStream类:完成文件或文件夹的压缩
            ZipOutputStream out=new ZipOutputStream(new FileOutputStream(zipfile));
            for(int i=0;i<srcfile.length;i++){
                FileInputStream in=new FileInputStream(srcfile[i]);
                out.putNextEntry(new ZipEntry(srcfile[i].getName()));
                int len;
                while((len=in.read(buf))>0){
                    out.write(buf,0,len);
                }
                out.closeEntry();
                in.close();
            }
            out.close();
            System.out.println("压缩完成.");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
       /**
        * 下载打包的文件
        * @param file
        * @param response
        */
       public void downloadZip(File file,HttpServletResponse response) {
           try {
               // 以流的形式下载文件。
               BufferedInputStream 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();
               file.delete();        //将生成的服务器端文件删除
            } 
            catch (IOException ex) {
               ex.printStackTrace();
           }
       }

    /** 
     * 删除目录(文件夹)以及目录下的文件 
     * @param   sPath 被删除目录的文件路径 
     * @return  目录删除成功返回true,否则返回false 
     */  
    public static boolean deleteDirectory(String sPath) {  
        //如果sPath不以文件分隔符结尾,自动添加文件分隔符  
        if (!sPath.endsWith(File.separator)) {  
            sPath = sPath + File.separator;  
        }  
        File dirFile = new File(sPath);  
        //如果dir对应的文件不存在,或者不是一个目录,则退出  
        if (!dirFile.exists() || !dirFile.isDirectory()) {  
            return false;  
        }  
        boolean flag = true;  
        //删除文件夹下的所有文件(包括子目录)  
        File[] files = dirFile.listFiles();  
        for (int i = 0; i < files.length; i++) {  
            //删除子文件  
            if (files[i].isFile()) {  
                flag = deleteFile(files[i].getAbsolutePath());  
                if (!flag) break;  
            } //删除子目录  
            else {  
                flag = deleteDirectory(files[i].getAbsolutePath());  
                if (!flag) break;  
            }  
        }  
        if (!flag) return false;  
        //删除当前目录  
        if (dirFile.delete()) {  
            return true;  
        } else {  
            return false;  
        }  
    }

      /**
      * 将base64字符串解码后返回字节数组
      */
     public static byte[] getFromBASE64ToByte(String s) {
      if (s == null)
       return null;
      BASE64Decoder decoder = new BASE64Decoder();
      try {
       byte[] b = decoder.decodeBuffer(s);
       return b;
      } catch (Exception e) {
       e.printStackTrace();
       return null;
      }
     }

 

//DAO

    public String exportFile1(String id) {
        // TODO Auto-generated method stub
        
        String sql = "SELECT T.ATTACHMENT FROM  LINE_FILE_TAB T WHERE T.ID = '"+id+"'";
        System.out.println("-------------============---------"+sql);
        String str = "";
        try {
            str = colbUtil.clobExport(sql, "ATTACHMENT");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return str;
    }

    public String clobExport(String exportSql,String filename) throws ClassNotFoundException, SQLException,IOException {
        // TODO Auto-generated method stub
        CLOB clob = null;
        DriverManager.registerDriver(new OracleDriver());
        Connection conn = DriverManager.getConnection(url, user, pwd);// 得到连接对象
        PreparedStatement stmt = conn.prepareStatement(exportSql);
        ResultSet rs = stmt.executeQuery();
        String content = "";
        if (rs.next()) {
            clob = (oracle.sql.CLOB) rs.getClob(filename); // 获得CLOB字段str
            // 注释: 用 rs.getString("str")无法得到 数据 ,返回的 是 NULL;
            if(clob == null){
                return content;
            }
            content = ClobToString(clob);
        }
        stmt.close();
        conn.close();
        // 输出结果
        return content;
    }

    // 将字CLOB转成STRING类型
    public String ClobToString(CLOB clob) throws SQLException, IOException {

        String reString = "";
        Reader is = clob.getCharacterStream();// 得到流
        BufferedReader br = new BufferedReader(is);
        String s = br.readLine();
        StringBuffer sb = new StringBuffer();
        while (s != null) {// 执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
            sb.append(s);
            s = br.readLine();
        }
        reString = sb.toString();
        return reString;
    }

转载于:https://my.oschina.net/zxj143/blog/730695

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值