IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> java.util.zip生成带目录的zip包 -> 正文阅读

[Java知识库]java.util.zip生成带目录的zip包


前言

背景:公司项目有一个文件导出要求,并且要按照特定的目录结构组织

一、java.util.zip 是什么

java.util.zip 是 java 提供的对于压缩文件读写的工具包

二、使用步骤

1. 基本对象


    class Node {
        String name; // 目录名称
        List<Node> nodes; // 子目录
        List<NodeFile> files; // 文件

        public Node(String name) {
            this.name = name;
        }
    }

    class NodeFile {
        File file; // 文件对象
        String name; // 真实文件名称

        public NodeFile(File file, String name) {
            this.file = file;
            this.name = name;
        }
    }
	// 进度对象
    class FileProcess {
        int total;
        int completed;
    }

2. 写数据

@Slf4j
public class ExportFile {
    private FileProcess fileProcess;

    public ExportFile() {
        fileProcess = new FileProcess();
    }

    public void writeZipFile(String zipDir, String zipName, List<Node> nodes) {
        ZipOutputStream zos = null;
        FileOutputStream fos = null;
        try {
            File file = new File(zipDir);
            if (!file.exists()) {
                file.mkdirs();
            }
            File zipFile = new File(zipDir + File.separator + zipName);
            zipFile.createNewFile();
            fos = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(fos);

            // 2. 循环创建目录,写入文件
            for (Node node : nodes) {
                writeFile(zos, "", node);
            }
        } catch (Exception e) {
            log.error("{}/{} 导出失败", zipDir, zipName, e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (Exception e) {
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                }
            }
        }
    }

    private void writeFile(ZipOutputStream zos, String dir, Node node) throws IOException {
        String currPath = StringUtils.isEmpty(dir) ? node.name : (dir + File.separator + node.name);
        writeFile2(zos, currPath, node.files);
        if (node.nodes == null) {
            return;
        }
        for (Node node1 : node.nodes) {
            writeFile(zos, currPath, node1);
        }
    }

    private void writeFile2(ZipOutputStream zos, String parentPath, List<NodeFile> files) throws IOException {
        if (CollectionUtils.isEmpty(files)) {
            return;
        }
        Map<String, Integer> fileIndex = new HashMap<>();
        for (NodeFile file : files) {
            Integer index;
            String path;
            if ((index = fileIndex.get(file.name)) == null) {
                fileIndex.put(file.name, 0);
                path = parentPath + File.separator + file.name;
            } else {
                index += 1;
                fileIndex.put(file.name, index);
                int index2 = file.name.lastIndexOf(".");
                path = parentPath + File.separator + file.name.substring(0, index2) + "(" + index + ")" + file.name.substring(index2);
            }
            zos.putNextEntry(new ZipEntry(path));
            copyFile(file.file, zos);
            fileProcess.completed++;
        }
    }

    private void copyFile(File file, ZipOutputStream zos) throws IOException {
        FileInputStream is = null;
        try {
            is = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int length;
            while ((length = is.read(bytes)) > 0) {
                zos.write(bytes, 0, length);
            }
        } catch (IOException e) {
            log.error("写文件失败 {}", file.getAbsolutePath(), e);
            throw e;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                }
            }
            try {
                zos.closeEntry();
            } catch (Exception e) {
            }
        }
    }

    public FileProcess getFileProcess() {
        return fileProcess;
    }

    public void setFileProcess(FileProcess fileProcess) {
        this.fileProcess = fileProcess;
    }

    public static void main(String[] args) {
        ExportFile file = new ExportFile();
        List<Node> list = new ArrayList<>();
        Node n = new Node("test");
        NodeFile f = new NodeFile(new File("/path/file.png"), "filename.png");
        n.files = Arrays.asList(f);
        list.add(n);
        file.writeZipFile("/path", "text.zip", list);
    }
}

总结

通过ZipOutputStream,每一个文件对应一个 ZipEntry

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2021-07-30 12:36:58  更:2021-07-30 12:38:42 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/2 1:54:42-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码