日曜プログラマの備忘録

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

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

2025-12-28 20:05:51
2026-01-11 12:01:55
目次
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

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

/* デスクトップパスの取得 */

Path desktopPath = null;
Path userHomePath = Paths.get(System.getProperty("user.home"));
String desktopPathString;

for (String name : new String[] {"Desktop", "デスクトップ"}) {
    desktopPath = userHomePath.resolve(name);

    if (Files.isDirectory(desktopPath)) {
        desktopPathString = desktopPath.toString();
        break;
    } else {
        desktopPath = null;
    }
}

if (desktopPath == null) {
    desktopPathString = userHomePath.toString();
}


/* ZIPファイルの解凍 */

String zipPathString = desktopPathString + File.separator + "sample.zip";
File parentDirectory = new File(desktopPathString + 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();

        if (!zipEntry.isDirectory()) {
            extractZipFile(zipInputStream, entryPathString);  // 「ZIPファイルの解凍」メソッドの呼び出し
        } 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』作者兼管理人