1
0

More than 1 year has passed since last update.

javaでダウンロードzipファイルを一時保存せず処理

Posted at

javaでネットワーク上のzipファイルを取得する場合はローカルの適当なディレクトリに一時保存してから解凍して処理が多いと思われる。内部実装はともかく、java上でzipファイルのダウンロードから処理までを完結する方法について。

環境

  • java 17

ソースコード

例として郵便番号(いわゆるken_all.csv)のzipファイルを読み込む。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipDownload {
  public static void main(String[] args) throws IOException {
    URL url = new URL("https://www.post.japanpost.jp/zipcode/dl/oogaki/zip/10gumma.zip");

    try (InputStream is = url.openStream();
        ZipInputStream zip = new ZipInputStream(is);
        InputStreamReader isr = new InputStreamReader(zip, "Shift_JIS");
        BufferedReader br = new BufferedReader(isr);) {

      ZipEntry entry;
      while ((entry = zip.getNextEntry()) != null) {
        System.out.println("####" + entry.getName());
        br.lines().forEach(System.out::println);
      }
    }
  }
}

zipファイルの中身の処理(ディレクトリの有無とか)や脆弱性対応(https://www.jpcert.or.jp/java-rules/ids04-j.html あたり参照)については省略している。

1
0
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
1
0