java网页下载网络文件
时间: 2024-10-26 20:17:56 浏览: 18
在Java中下载网络文件通常涉及到使用HttpURLConnection或者更现代的HttpClient API,这里以简单的HttpURLConnection示例来说明:
```java
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
public class FileDownloader {
public static void downloadFile(String urlString) throws Exception {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int fileLength = connection.getContentLengthLong(); // 获取文件长度
FileOutputStream outputStream = new FileOutputStream("path/to/downloaded/file"); // 输出流到本地文件
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = connection.getInputStream().read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead); // 读取并写入文件
}
outputStream.close();
connection.disconnect();
}
}
```
在这个例子中,你需要将`urlString`替换为你想要下载的实际URL,然后程序会下载指定URL的资源并保存到本地。
阅读全文