zip导出demo

 /**
     * 导出文件
     *
     * @param response
     * @throws Exception
     */
    public void exportQytzpz(HttpServletRequest request, UserData userData, HttpServletResponse response, String year, String month) throws Exception {
        month = month.startsWith("0") ? month.replace("0", "") : month;
        SqlParamDTO sqlParamDTO = qytzshDAO.makeQytzpzParamDTO(userData, year, month);
        String fileName = "历史台账信息";
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        try {
            //查台账
            conn = CommonDAO.getConnection();
            pstm = conn.prepareStatement(sqlParamDTO.getSql());
            sqlParamDTO.setParameterValues(pstm);
            rs = pstm.executeQuery();
            String title = year + "年" + month + "月工价台账凭证";
            String rootPath = "";
            if (StringUtils.isNotEmpty(SystemParameter.OUTER_SHAREFILE_PATH)) {
                rootPath = SystemParameter.OUTER_SHAREFILE_PATH;
            } else {
                rootPath = request.getRealPath(CommonConstant.EXPORT_DATA_FILE_PATH);
            }
            rootPath = rootPath + File.separator + "ScTzUploadPics" + File.separator;
            String source = rootPath + File.separator + title;
            //创建图片文件目录
            createpicDir(rootPath, rs, title);
            //打包zip,导出
            ServletOutputStream out = response.getOutputStream();
            //将zip以流的形式输出到前台
            response.setHeader("content-type", "application/octet-stream");
            response.setCharacterEncoding("utf-8");
            // 设置浏览器响应头对应的Content-disposition
            //参数中 testZip 为压缩包文件名,尾部的.zip 为文件后缀
            response.setHeader("Content-disposition",
                    "attachment;filename=" + new String(title.getBytes("gbk"), "iso8859-1") + ".zip");
            toZip(source, out, true);
            //删除过度文件
            deleteDir(source);
        } catch (ThtfException e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                rs.close();
            }
        }

    }

    /**
     * 删除过度文件夹
     *
     * @param path
     * @return
     */
    private boolean deleteDir(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return false;
        }
        if (file.isFile()) {
            return file.delete();
        }
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isFile()) {
                if (!f.delete()) {
                    return false;
                }
            } else {
                if (!this.deleteDir(f.getAbsolutePath())) {
                    return false;
                }
            }
        }
        return file.delete();
    }

    /**
     * 压缩成ZIP 方法
     *
     * @param srcDir           压缩文件夹路径
     * @param out              输出流
     * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    private void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
            throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
            long end = System.currentTimeMillis();
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 递归压缩方法
     *
     * @param sourceFile       源文件
     * @param zos              zip输出流
     * @param name             压缩后的名称
     * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception
     */
    private void compress(File sourceFile, ZipOutputStream zos, String name,
                          boolean KeepDirStructure) throws Exception {
        byte[] buf = new byte[1024];
        if (sourceFile.isFile()) {
            // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if (KeepDirStructure) {
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件,不需要文件的copy
                    zos.closeEntry();
                }

            } else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
                    } else {
                        compress(file, zos, file.getName(), KeepDirStructure);
                    }

                }
            }
        }
    }
  
private void createpicDir(String rootPath, ResultSet rs, String title) throws SQLException, IOException { FileInputStream fis = null; FileOutputStream fos = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; try { while (rs.next()) { QytzDTO qytzDTO = getQytzDTO(rs); String price5pic = qytzDTO.getPrice5pic(); String price20pic = qytzDTO.getPrice20pic(); String qymc = qytzDTO.getQymc(); String ggpmc = qytzDTO.getGgpmc(); String ggplx = qytzDTO.getGgplx(); ggplx = ggplx == "1" ? "购进" : "出厂"; //5日 if (StringUtils.isNotEmpty(price5pic)) { String[] pics = price5pic.split(","); for (int i = 0; i < pics.length; i++) { String[] suffixs = pics[i].split("\\."); String inPath = rootPath + File.separator + pics[i]; String outPath = rootPath + File.separator + title + File.separator + qymc + File.separator + ggplx + "-" + ggpmc + "-5日" + "(" + (i + 1) + ")." + suffixs[1]; File inFile = new File(inPath); File outFile = new File(outPath); if (!inFile.exists()) { continue; } fis = new FileInputStream(inFile); bis = new BufferedInputStream(fis); //检查父目录 if (!outFile.exists()) { outFile.mkdirs(); outFile.delete(); } fos = new FileOutputStream(outFile); bos = new BufferedOutputStream(fos); int len; byte[] buffer = new byte[2048]; while ((len = bis.read(buffer)) != -1) { bos.write(buffer, 0, len); } fos.flush(); bos.flush(); } } //20日 if (StringUtils.isNotEmpty(price20pic)) { String[] pics = price20pic.split(","); for (int i = 0; i < pics.length; i++) { String[] suffixs = pics[i].split("\\."); String inPath = rootPath + File.separator + pics[i]; String outPath = rootPath + File.separator + title + File.separator + qymc + File.separator + ggplx + "-" + ggpmc + "-20日" + "(" + (i + 1) + ")." + suffixs[1]; File inFile = new File(inPath); File outFile = new File(outPath); if (!inFile.exists()) { continue; } fis = new FileInputStream(inFile); bis = new BufferedInputStream(fis); //检查父目录 if (!outFile.exists()) { outFile.mkdirs(); outFile.delete(); } fos = new FileOutputStream(outFile); bos = new BufferedOutputStream(fos); int len; byte[] buffer = new byte[2048]; while ((len = bis.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.flush(); } } } } catch (IOException e) { e.printStackTrace(); } finally { if (bis != null) { bis.close(); } if (bos != null) { bos.close(); } if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } System.gc(); } }

 

posted @ 2022-08-23 18:47  厚我  阅读(29)  评论(0编辑  收藏  举报