java实现http下载
时间: 2023-11-02 21:03:07 浏览: 43
Java实现HTTP下载可以使用Java标准库中的URLConnection类来实现。下面是一个简单的示例代码:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class HttpDownloader {
public static void main(String[] args) {
String fileUrl = "http://example.com/file.txt"; // 下载文件的URL
String savePath = "C:/path/to/save/file.txt"; // 文件保存路径
try {
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
FileOutputStream outputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("文件下载成功!");
} catch (IOException e) {
System.err.println("文件下载出错:" + e.getMessage());
}
}
}
```
这个示例中,我们首先创建一个URL对象并打开连接,然后获取输入流来读取下载文件的数据,将其写入到文件输出流中。最后关闭输入输出流,完成文件的下载。需要注意的是,以上代码仅适用于下载小文件,如果要下载大文件或者需要实现断点续传等功能,还需进行相应的优化和处理。