5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaでZIPファイルを扱う

Last updated at Posted at 2016-07-15

JavaでZIPファイルを読み込む。サンプルではファイル名一覧とbyte[]でデータを読み込んだ上でサイズを表示している。

以前の方法はZipInputStreamを使う。

public class ZipDemo {
    public static final String PATH = "/path/to/zipfile.zip";

    public static void main(final String[] args) throws IOException {
        final Path zipfile = Paths.get(PATH);
        try (ZipInputStream zis = new ZipInputStream(
                new ByteArrayInputStream(Files.readAllBytes(zipfile)));) {
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                if (entry.isDirectory()) {
                    continue;
                }
                System.out.printf("%s - %d\n", entry.getName(),
                        IOUtils.toByteArray(zis).length);

            }
        }
    }
}

NIO2のFilesystemsを使うとコールバックを使ってわかりやすく書ける。

public class ZipDemo {
    public static final String PATH = "/path/to/zipfile.zip";

    public static void main(final String[] args) throws IOException {
        final Path zipfile = Paths.get(PATH);

        try (FileSystem fs = FileSystems.newFileSystem(zipfile, null)) {
            final Path path = fs.getPath("/");
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(final Path file,
                                                 final BasicFileAttributes attrs) throws IOException {
                    System.out.printf("%s - %d\n", file,
                            Files.readAllBytes(file).length);
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    }
}
5
4
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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?