java实现文件及文件夹打包

使用jar包:apache内置的打包工具

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

public void filePackage(HttpServletRequest request, HttpServletResponse response) {
        List<Map<String, String>> querySelfCheckingList = queryCurrentPage(request, response);// 获取当前页巡检信息
        String rootPath = request.getRealPath("/");
        String sourcePath = rootPath + "temp_upload/";
        File selfCheckingFolder = new File(sourcePath);// 创建文件夹,用于存放压缩包和其他文件夹
        if (!selfCheckingFolder.exists()) {
            selfCheckingFolder.mkdirs();
        }

        String zipName = "微信自助巡检.zip";// 定义压缩包名称
        File zipFile = new File(zipName);
        File terminalIdPath = null;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        OutputStream out = null;
        if (null != querySelfCheckingList && querySelfCheckingList.size() > 0) {
            for (Map<String, String> map : querySelfCheckingList) {
                String fssId = map.get("fssId");
                String terminalId = map.get("terminalNo"); // 终端编号,命名当前记录的文件夹名称
                logger.info(">>>>>>>SelfCheckingController>>>>>filePackage:fssId:{},terminalId:{}", fssId, terminalId);

                String path = terminalId + File.separator;
                terminalIdPath = new File(sourcePath + path);// 创建以终端号为名的文件夹,用于存放每条记录的图片
                if (!terminalIdPath.exists()) {
                    // 创建terminalIdPath文件夹
                    terminalIdPath.mkdirs();
                }
                // 开始下载图片,并保存到本地
                FileOutputStream outputStream = null;
                List<String> asList = split(fssId);
                for (int i = 0; i < asList.size(); i++) {
                    try {
                        byte[] bytes = fssClient.getFileContent(APP_CODE, asList.get(i), 30000);// 下载资质
                        CheckingFile checkingFile = new CheckingFile();
                        String fileName = String.valueOf(new Date().getTime()) + String.valueOf(i);// 定义文件名,默认以当前时间命名
                        checkingFile.setFssid(asList.get(i));
                        List<CheckingFile> checkingFileList = checkingFileService
                                .queryCheckingFileByModel(checkingFile);
                        if (null != checkingFileList && checkingFileList.size() > 0) {
                            fileName = checkingFileList.get(0).getFileName();
                        }

                        File sourceFile = new File(sourcePath + path + fileName + ".jpg");

                        outputStream = FileUtils.openOutputStream(sourceFile);
                        outputStream.write(bytes);
                    } catch (Exception e) {
                        logger.error(">>>>>>>SelfCheckingController>>>>>filePackage:图片下载失败!{}", e);
                    } finally {
                        IoUtil.close(outputStream);
                    }
                }
            }
        }
        try {
            File files = new File(sourcePath);
            fos = new FileOutputStream(zipName);
            zos = new ZipOutputStream(fos);
            writeZip(files, "", zos);

        } catch (FileNotFoundException e) {
            logger.error(">>>>>>>SelfCheckingController>>>>>filePackage:文件夹写入失败!{}", e);
        }
        try {
            out = response.getOutputStream();
            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String(zipName.getBytes("GB2312"), "ISO-8859-1"));
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            out.write(FileUtils.readFileToByteArray(zipFile));
            out.flush();
            out.close();
        } catch (IOException e) {
            logger.error(">>>>>>>SelfCheckingController>>>>>filePackage:响应失败失败!{}", e);
        }
    }

    /**
     * @Title: split
     */
    private List<String> split(String fssId) {
        String[] split = null;
        List<String> asList = new ArrayList<String>();// 分割fssId字符串数组,放入list
        if (StringUtils.isNotEmpty(fssId) && fssId.indexOf(",") != -1) {
            split = fssId.split(",");
            asList = Arrays.asList(split);
        } else {
            asList.add(fssId);
        }
        return asList;
    }

    /**
     * 写入压缩包
     */
    public void writeZip(File file, String parentPath, ZipOutputStream zos) {
        if (file.exists()) { // 需要压缩的文件夹是否存在
            if (file.isDirectory()) {// 判断是否是文件夹

                parentPath += file.getName() + File.separator; // 文件夹名称 + "/"
                File[] files = file.listFiles(); // 获取文件夹下的文件夹或文件
                if (files.length != 0) {
                    for (File f : files) {
                        writeZip(f, parentPath, zos);
                    }
                } else { // 空目录则创建当前目录
                    try {
                        zos.putNextEntry(new ZipEntry(parentPath));
                    } catch (IOException e) {
                        logger.error(">>>>>>>SelfCheckingController>>>>>writeZip:创建当前目录失败!{}", e);
                    }
                }
            } else {
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(file);
                    ZipEntry ze = new ZipEntry(parentPath + file.getName());
                    zos.putNextEntry(ze);
                    byte[] content = new byte[1024];
                    int len;
                    while ((len = fis.read(content)) != -1) {
                        zos.write(content, 0, len);
                        zos.flush();
                    }
                } catch (Exception e) {
                    logger.error(">>>>>>>SelfCheckingController>>>>>writeZip:文件未找到!{}", e);
                } finally {
                    try {
                        if (fis != null) {
                            fis.close();
                            if (file != null && file.exists()) {
                                file.delete();
                            }
                        }
                    } catch (IOException e) {
                        logger.error(">>>>>>>SelfCheckingController>>>>>writeZip:输入流关闭失败!{}", e);
                    }
                }
            }
        }

    }

效果如下:

解压后文件夹:


猜你喜欢

转载自blog.csdn.net/qiaoxin666/article/details/80509317