2
3

More than 1 year has passed since last update.

JavaでNIO.2を使いつつZIP圧縮&解凍

Last updated at Posted at 2022-04-28

環境

JDK 17を使っています。たぶん、多少バージョンが違っていても同じように動くと思います。

圧縮

test1.txt・test2.txt・test3.txtを圧縮して、test.zipを作成します。

import文
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
コード本体
List<Path> targetFileList = List.of(
        Path.of("test1.txt"),
        Path.of("test2.txt"),
        Path.of("test3.txt")
);

Path zipFile = Path.of("test.zip");

try (OutputStream os = Files.newOutputStream(zipFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
     ZipOutputStream zos = new ZipOutputStream(os, StandardCharsets.UTF_8)) {
    for (Path targetFile : targetFileList) {
        ZipEntry zipEntry = new ZipEntry(targetFile.getFileName().toString());
        zos.putNextEntry(zipEntry);
        byte[] bytes = Files.readAllBytes(targetFile);
        zos.write(bytes);
        zos.closeEntry();
    }
} catch (IOException e) {
    // 適切に例外処理してください
}

解凍

圧縮の際に作成したZIPファイルを、resultフォルダに解答します。

import文
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
コード本体
Path zipPath = Path.of("test.zip");
Path dir = Path.of("result");

try (ZipFile zipFile = new ZipFile(zipPath.toFile(), StandardCharsets.UTF_8);
     Stream<? extends ZipEntry> stream = zipFile.stream()) {
    List<Path> uncompressedFileList = stream.filter(zipEntry -> zipEntry.isDirectory() == false)
            .map(zipEntry -> {
                try (InputStream is = zipFile.getInputStream(zipEntry)) {
                    byte[] bytes = is.readAllBytes();
                    Path uncompressedFile = Path.of(dir.toString(), zipEntry.getName());
                    Files.write(uncompressedFile, bytes, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
                    return uncompressedFile;
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                }
            })
            .toList();
} catch (IOException e) {
    // 適切に例外処理してください
}

参考にした記事

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3