日曜プログラマの備忘録

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

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

2025-12-27 12:54:00
2026-01-11 12:01:35
目次
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;

/* デスクトップパスの取得 */

Path desktopPath = null;
Path userHomePath = Paths.get(System.getProperty("user.home"));
String desktopPathString;

for (String name : new String[] {"Desktop", "デスクトップ"}) {
    desktopPath = userHomePath.resolve(name);

    if (Files.isDirectory(desktopPath)) {
        desktopPathString = desktopPath.toString();
        break;
    } else {
        desktopPath = null;
    }
}

if (desktopPath == null) {
    desktopPathString = userHomePath.toString();
}


/* ファイルのダウンロード */

String zipURLString = "https://www.sunday-programmer.com/sample.zip";  // ダウンロード元ファイルのURL
String zipPathString = desktopPathString + File.separator + "sample.zip";  // ダウンロード先ファイルのパス

try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new URL(zipURLString).openStream());
     FileOutputStream fileOutputStream = new FileOutputStream(zipPathString)) {
    int bytes;
    byte[] dataBuffer = new byte[16384];

    while ((bytes = bufferedInputStream.read(dataBuffer)) != -1) {
        fileOutputStream.write(dataBuffer, 0, bytes);
    }
} catch (IOException e) {
    System.out.println("ファイルのダウンロード中にエラーが発生しました! (" + e.getMessage() + ")");
}

この記事を書いた人

ASAWA Kōichi

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