java 从URL 下载文件
时间: 2023-08-25 07:05:11 浏览: 51
在 Java 中,可以使用 URL 类来下载文件。以下是一个简单的示例代码:
```java
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
public class FileDownload {
public static void main(String[] args) throws IOException {
String fileUrl = "https://example.com/file.txt";
String saveDir = "C:/Downloads/";
String fileName = "file.txt";
downloadFile(fileUrl, saveDir, fileName);
}
public static void downloadFile(String fileUrl, String saveDir, String fileName) throws IOException {
URL url = new URL(fileUrl);
BufferedInputStream in = new BufferedInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(saveDir + fileName);
byte[] dataBuffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytesRead);
}
fileOutputStream.close();
in.close();
System.out.println("File downloaded successfully.");
}
}
```
上述代码将从 `fileUrl` 指定的 URL 下载文件,并将其保存在 `saveDir` 目录下的 `fileName` 文件中。在下载文件时,代码使用缓冲输入流读取数据,然后使用文件输出流将数据写入本地文件。最后关闭输入流和输出流,下载完成。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)