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 あたり参照)については省略している。