如何使用Java程序读取zip文档?

  Java   6分钟   686浏览   0评论

描述

ZIP文档(通常)以压缩格式存储了一个或多个文件,每个ZIP文档都有一个头,包含诸如每个文件名字和所使用的压缩方法等信息。在Java中,可以使用ZipInputStream来读人ZIP文档。你可能需要浏览文档中每个单独的项,getNextEntry方法就可以返回一个描述这些项的ZipEntry类型的对象。

编码

1.首先,引入需要的maven依赖

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

2.编码实现读取zip包下的所有文件

package com.zou.io;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * @author: 邹祥发
 * @date: 2021/11/11 10:38
 */
public class ZipDemo {
    public static void main(String[] args) {
        File file = new File("C:\\Users\\15654\\Desktop\\img.zip");
        ZipFile zipFile = null;
        ZipInputStream zin = null;
        FileInputStream fis = null;
        try {
            Charset gbk = Charset.forName("GBK");
            zipFile = new ZipFile(file, gbk);
            fis = new FileInputStream(file);
            zin = new ZipInputStream(fis, gbk);

            ZipEntry ze;
            while ((ze = zin.getNextEntry()) != null) {
                String path = ze.getName();
                System.out.println(path);
                if (!ze.isDirectory() && ze.toString().endsWith("txt")) {
                    InputStream inputStream = zipFile.getInputStream(ze);
                    List<String> texts = IOUtils.readLines(inputStream);
                    for (String text : texts) {
                        System.out.println("  " + text);
                    }
                    inputStream.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (zin != null) {
                    zin.closeEntry();
                    zin.close();
                }
                if (fis != null)
                    fis.close();
                if (zipFile != null)
                    zipFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

注:该目录为我本机压缩包路径。

File file = new File("C:\Users\15654\Desktop\img.zip");

实现效果

1.首先,看一下img文件夹中的内容。

2.运行代码,控制台成功打印出zip包下的所有文件。

如果你觉得文章对你有帮助,那就请作者喝杯咖啡吧☕
微信
支付宝
  0 条评论