日曜プログラマの備忘録

『日曜プログラマ.com』公式ブログ

作成したディレクトリ内にZIPファイルを解凍する

2025-12-28 20:05:51
2025-12-28 21:49:24
目次
import java.io.BufferedOutputStream;
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;

デスクトップ上にディレクトリを作成し、その中にZIPファイルを解凍する。

String zipPathString = System.getProperty("user.home") + File.separator + "Desktop" + File.separator + "sample.zip";
File parentDirectory = new File(System.getProperty("user.home") + File.separator + "Desktop" + File.separator + "sample");
parentDirectory.mkdir();

try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(new File(zipPathString)))) {
    ZipEntry zipEntry = zipInputStream.getNextEntry();
    String entryPathString;
    File entryDirectory;

    while (zipEntry != null) {
        entryPathString = parentDirectory.getPath() + File.separator + zipEntry.getName();
        System.out.println(entryPathString);

        if (!zipEntry.isDirectory()) {
            extractZipFile(zipInputStream, entryPathString);
        } else {
            entryDirectory = new File(entryPathString);
            entryDirectory.mkdirs();
        }

        zipInputStream.closeEntry();
        zipEntry = zipInputStream.getNextEntry();
    }
} catch (IOException e) {
    System.out.println("ZIPファイルの解凍中にエラーが発生しました! (" + e.getMessage() + ")");
}

ZIPファイルの解凍メソッド

void extractZipFile(ZipInputStream zipInputStream, String entryPathString) {
    try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(entryPathString))) {
        int bytes;
        byte[] dataBuffer = new byte[16384];

        while ((bytes = zipInputStream.read(dataBuffer)) != -1) {
            bufferedOutputStream.write(dataBuffer, 0, bytes);
        }
    } catch (IOException e) {
        System.out.println("ZIPファイルの解凍中にエラーが発生しました! (" + e.getMessage() + ")");
    }
}

この記事を書いた人

ASAWA Kōichi

『日曜プログラマ.com』作者兼管理人