Java Download File from URL Example
In Java, you can use the java.net.URL class to download files. Below is a simple example code:
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
public class FileDownloader {
public static void downloadFile(String fileUrl, String savePath) throws IOException {
URL url = new URL(fileUrl);
BufferedInputStream inputStream = new BufferedInputStream(url.openStream());
FileOutputStream outputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer, 0, 1024)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
}
public static void main(String[] args) {
String fileUrl = "https://example.com/file.txt";
String savePath = "/path/to/save/file.txt";
try {
downloadFile(fileUrl, savePath);
System.out.println("文件下载完成");
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the example code above, the downloadFile method takes the URL of the file and the path to save it as parameters. It opens an input stream using the URL class and reads it using BufferedInputStream, then writes it to the specified file using FileOutputStream. Finally, it closes the input and output streams.
In the main method, you can replace fileUrl and savePath with the URL of the file you want to download and the path where you want to save it.