日曜プログラマの備忘録

『日曜プログラマ.com』公式ブログ

デスクトップ上にファイルをダウンロード

2025-12-27 12:54:00
2025-12-27 12:56:31
目次
/* デスクトップパスの取得 */

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() + ")");
}

この記事を書いた人

ASAWA Kōichi

『日曜プログラマ.com』作者兼管理人