Java 从网上下载文件的几种方式实例代码详解
在Java编程中,有时候需要从网上下载文件,比如下载图片、音频、视频等资源文件。本文将详细讲解Java 从网上下载文件的几种方式,希望可以帮助大家实现这个需求。
1.使用URL类下载文件
使用URL类可以轻松地实现从网上下载文件。实现的过程如下:
public static void downloadFile(String urlString, String savePath) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
InputStream inputStream = conn.getInputStream();
byte[] getData = readInputStream(inputStream);
File file = new File(savePath);
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(getData);
fileOutputStream.close();
inputStream.close();
}
private static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
byteArrayOutputStream.close();
return byteArrayOutputStream.toByteArray();
}
其中,downloadFile函数用于下载文件,输入参数有urlString和savePath,分别表示下载的资源文件URL和本地存储路径。
2.使用Apache的HttpClient类下载文件
另一种从网上下载文件的方式是使用Apache的HttpClient类。具体实现过程如下:
public static void downloadFile(String urlString, String savePath) throws IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(urlString);
CloseableHttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
byte[] getData = readInputStream(inputStream);
File file = new File(savePath);
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(getData);
fileOutputStream.close();
entity.getContent().close();
response.close();
}
private static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
byteArrayOutputStream.close();
return byteArrayOutputStream.toByteArray();
}
HttpClient需要引入以下两个依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.6</version>
</dependency>
示例
假设我们需要从百度首页下载百度logo。那么可以使用以下代码:
String url = "https://www.baidu.com/img/baidu_jgylogo3.gif";
String savePath = "/Users/work/desktop/baidu_jgylogo3.gif";
// 使用URL类下载文件
DownloadUtil.downloadFile(url, savePath);
// 使用HttpClient下载文件
DownloadUtil.downloadFile(url, savePath);
在实际编程中,我们只需要根据实际需求替换url和savePath参数即可。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java 从网上下载文件的几种方式实例代码详解 - Python技术站