目次
/* デスクトップパスの取得 */
String desktopPathString;
if (Files.exists(Paths.get(System.getProperty("user.home") + File.separator + "Desktop"))) {
desktopPathString = System.getProperty("user.home") + File.separator + "Desktop";
} else {
desktopPathString = System.getProperty("user.home") + File.separator + "デスクトップ"; // 環境により「デスクトップ」(日本語)の場合あり
}
/* ファイルのダウンロード */
String zipURLString = "https://www.post.japanpost.jp/zipcode/dl/kogaki/zip/ken_all.zip"; // ダウンロード元ファイルのURL
String zipPathString = desktopPathString + File.separator + "ken_all.zip"; // ダウンロード先ファイルのパス
byte[] dataBuffer = new byte[16384];
int bytes;
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new URL(zipURLString).openStream());
FileOutputStream fileOutputStream = new FileOutputStream(zipPathString)) {
while ((bytes = bufferedInputStream.read(dataBuffer)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytes);
}
} catch (IOException e) {
System.out.println("ファイルのダウンロード中にエラーが発生しました! (" + e.getMessage() + ")");
}