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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
java.utilJava中一个非常重要的,它含了一些在Java应用程序中经常使用的类,比如集合类、日期与时间处理类、随机数生成类、正则表达式类等。下面是java.util中一些常用类的使用方法详解。 1. 集合类 Java集合框架定义了一组接口用于表示集合,以及一些实现这些接口的类。这些类括ArrayList,LinkedList,HashSet,TreeSet,HashMap,TreeMap等。它们提供了各种方法来添加、删除、查找和遍历集合元素。 以ArrayList为例,以下是一些常用方法: ``` // 创建ArrayList对象 ArrayList<String> list = new ArrayList<String>(); // 添加元素 list.add("apple"); list.add("banana"); list.add("orange"); // 获取元素 String first = list.get(0); String last = list.get(list.size() - 1); // 遍历元素 for (String fruit : list) { System.out.println(fruit); } // 删除元素 list.remove("apple"); ``` 2. 日期与时间处理类 Java提供了多种处理日期和时间的类,括Date,Calendar,SimpleDateFormat等。其中,Date类表示日期和时间,Calendar类是一个抽象类,用于操作日期和时间,SimpleDateFormat类用于格式化日期和时间。 以下是一个使用SimpleDateFormat类将日期格式化为指定字符串的示例: ``` Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formattedDate = formatter.format(date); System.out.println(formattedDate); ``` 3. 随机数生成Java提供了Random类用于生成随机数。它含了多个方法,可以生成不同类型的随机数,如整数、浮点数、布尔值等。 以下是一个生成1到6之间的随机整数的示例: ``` Random rand = new Random(); int num = rand.nextInt(6) + 1; System.out.println(num); ``` 4. 正则表达式类 Java提供了Pattern和Matcher类用于处理正则表达式。Pattern类表示正则表达式,Matcher类用于在给定输入字符串中匹配该正则表达式。 以下是一个使用正则表达式匹配邮政编码的示例: ``` String zipCodePattern = "\\d{5}"; Pattern pattern = Pattern.compile(zipCodePattern); String input = "12345"; Matcher matcher = pattern.matcher(input); if (matcher.matches()) { System.out.println("Valid zip code"); } else { System.out.println("Invalid zip code"); } ``` 以上是java.util中一些常用类的使用方法详解,这些类在Java应用程序中经常用到,掌握它们的使用方法对于Java开发者来说非常重要。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值