Java 解压 Zip 文件:简单易懂的步骤和示例

使用 Java 的 'java.util.zip' 包可以轻松解压 Zip 文件。下面是一个简单的示例,展示如何使用 Java 解压 Zip 文件:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnzipExample {
    public static void main(String[] args) {
        String zipFilePath = 'path/to/your/zip/file.zip';
        String destinationFolderPath = 'path/to/destination/folder';

        try {
            unzip(zipFilePath, destinationFolderPath);
            System.out.println('解压成功');
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void unzip(String zipFilePath, String destinationFolderPath) throws IOException {
        byte[] buffer = new byte[1024];

        // 创建目标文件夹
        File destinationFolder = new File(destinationFolderPath);
        if (!destinationFolder.exists()) {
            destinationFolder.mkdir();
        }

        // 创建 ZipInputStream 对象
        ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath));

        // 获取 ZipEntry 对象并逐个解压
        ZipEntry zipEntry = zipInputStream.getNextEntry();
        while (zipEntry != null) {
            String fileName = zipEntry.getName();
            File newFile = new File(destinationFolderPath + File.separator + fileName);

            // 创建父文件夹
            new File(newFile.getParent()).mkdirs();

            // 创建输出流
            FileOutputStream fileOutputStream = new FileOutputStream(newFile);

            // 读取并写入文件
            int length;
            while ((length = zipInputStream.read(buffer)) > 0) {
                fileOutputStream.write(buffer, 0, length);
            }

            // 关闭输出流
            fileOutputStream.close();

            // 关闭当前 ZipEntry 并获取下一个 ZipEntry
            zipInputStream.closeEntry();
            zipEntry = zipInputStream.getNextEntry();
        }

        // 关闭 ZipInputStream
        zipInputStream.close();
    }
}

你需要将 'zipFilePath' 替换为要解压的 Zip 文件的路径,将 'destinationFolderPath' 替换为解压后文件的目标路径。

这个示例会将 Zip 文件中的所有内容解压到指定的目标文件夹中。

Java 解压 Zip 文件:简单易懂的步骤和示例

原文地址: https://www.cveoy.top/t/topic/p0wu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录