How to read a zip folder in Java?

To read a zip file folder, you can use the ZipInputStream class in Java. Below is a simple example code that demonstrates how to read all the files in a zip file folder.

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ReadZipFolder {
    public static void main(String[] args) {
        try {
            ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream("path/to/your/zipfile.zip"));

            ZipEntry entry = zipInputStream.getNextEntry();

            while (entry != null) {
                if (!entry.isDirectory()) {
                    System.out.println("File: " + entry.getName());

                    // 读取文件内容
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

                    while ((bytesRead = zipInputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }

                    System.out.println("Content: " + new String(outputStream.toByteArray()));
                    outputStream.close();
                }

                entry = zipInputStream.getNextEntry();
            }

            zipInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, we start by creating a ZipInputStream object and passing in the zip file we want to read. We then use the getNextEntry() method to read each file in the zip package one by one, checking if each entry is a folder. If it’s not a folder, we read the file content and output it.

Please note that this is just a simple example code, additional exception handling and more logic may be needed for actual use to handle different scenarios.

bannerAds