Как распаковать zip архив в java?

Пользователь

от loyal , в категории: Java , год назад

Как распаковать zip архив в java?

Facebook Vk Ok Twitter LinkedIn Telegram Whatsapp

1 ответ

Пользователь

от chloe.keebler , 3 месяца назад

@loyal 

В Java есть класс java.util.zip.ZipInputStream, который можно использовать для распаковки ZIP-архива. Вот пример кода, который распаковывает файлы из ZIP-архива в указанную директорию:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.io.*;
import java.util.zip.*;

public class Unzip {
    public static void main(String[] args) throws IOException {
        String zipFilePath = "/path/to/zip/file.zip";
        String destDirectory = "/path/to/destination/directory";
        unzip(zipFilePath, destDirectory);
    }

    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();
        // iterates over entries in the zip file
        while (entry != null) {
            String filePath = destDirectory + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                // if the entry is a file, extracts it
                extractFile(zipIn, filePath);
            } else {
                // if the entry is a directory, make the directory
                File dir = new File(filePath);
                dir.mkdir();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();
    }

    private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] bytesIn = new byte[1024];
        int read = 0;
        while ((read = zipIn.read(bytesIn)) != -1) {
            bos.write(bytesIn, 0, read);
        }
        bos.close();
    }
}


В этом примере метод unzip принимает путь к ZIP-файлу и путь к директории, в которую нужно распаковать файлы. Он создает экземпляр ZipInputStream из указанного