Java

java中如何解压zip文件到指定目录

小亿
384
2024-04-19 09:44:14
栏目: 编程语言

在Java中解压ZIP文件到指定目录可以使用java.util.zip包中的ZipInputStream类和ZipEntry类来实现。下面是一个示例代码:

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 unzip(String zipFilePath, String destDirectory) throws IOException {
        File destDir = new File(destDirectory);
        if (!destDir.exists()) {
            destDir.mkdir();
        }

        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
        ZipEntry entry = zipIn.getNextEntry();

        while (entry != null) {
            String filePath = destDirectory + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                extractFile(zipIn, filePath);
            } else {
                File dir = new File(filePath);
                dir.mkdir();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }

        zipIn.close();
    }

    private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = zipIn.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
        }
    }

    public static void main(String[] args) {
        String zipFilePath = "example.zip";
        String destDirectory = "unzipped";
        
        try {
            unzip(zipFilePath, destDirectory);
            System.out.println("ZIP file has been successfully extracted to " + destDirectory);
        } catch (IOException e) {
            System.out.println("Error occurred during ZIP file extraction: " + e.getMessage());
        }
    }
}

在上面的示例代码中,unzip方法接收ZIP文件的路径和目标目录的路径作为参数,然后使用ZipInputStream类逐个解析ZIP文件中的条目,并根据条目的类型(文件或目录)进行解压操作。解压文件时,调用extractFile方法来将文件内容写入到目标目录中。最后,在main方法中调用unzip方法来解压ZIP文件到指定目录。

0
看了该问题的人还看了