Java でファイルをローカルにダウンロードする方法
Java でファイルをローカルにダウンロードするには、Java の URL クラスと InputStream クラスを使用できます。以下のコードは簡単なサンプルです。
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class FileDownloader {
public static void main(String[] args) {
String fileUrl = "https://example.com/file.txt";
String savePath = "C:\\downloads\\file.txt";
try {
downloadFile(fileUrl, savePath);
System.out.println("文件下载成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
private static void downloadFile(String fileUrl, String savePath) throws IOException {
URL url = new URL(fileUrl);
try (InputStream inputStream = url.openStream();
FileOutputStream outputStream = new FileOutputStream(savePath)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
}
}
上記の例において、fileUrlはダウンロード対象のファイルのURLアドレスで、savePathはローカルに保存するパスです。downloadFileメソッドは、URLクラスを用いてURLストリームを開き、FileOutputStreamクラスを用いてファイルをローカルに書き込みます。URLストリームからデータを逐次読み込んでローカルファイルへ書き込み、ストリームの末尾に達するまで繰り返します。