java 实现浏览器下载文件
时间: 2023-09-04 16:12:11 浏览: 104
要在 Java 中实现浏览器下载文件,可以使用 Java 的 URL 和 HttpURLConnection 类。以下是实现的步骤:
1. 构建 URL 对象,指定要下载的文件的 URL。
2. 打开 HttpURLConnection 连接,并设置请求头,指定请求方式为 GET。
3. 获取 HttpURLConnection 的输入流,读取文件内容。
4. 将文件内容写入到本地文件中。
示例代码:
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileDownload {
public static void main(String[] args) {
String fileUrl = "http://example.com/file.pdf"; // 要下载的文件 URL
String savePath = "/path/to/save/file.pdf"; // 本地保存文件的路径
try {
URL url = new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
InputStream inputStream = conn.getInputStream();
BufferedInputStream in = new BufferedInputStream(inputStream);
FileOutputStream fileOutputStream = new FileOutputStream(savePath);
BufferedOutputStream out = new BufferedOutputStream(fileOutputStream);
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
out.close();
in.close();
conn.disconnect();
System.out.println("文件下载完成");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以上代码将会从指定的 URL 下载文件,并保存到指定的本地路径。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)