91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

Java實現下載文件的6種方式

小云
560
2023-08-08 11:43:29
欄目: 編程語言

  1. 使用URL類的openStream()方法下載文件:
URL url = new URL(fileUrl);
InputStream inputStream = url.openStream();
FileOutputStream outputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
  1. 使用URLConnection類下載文件:
URL url = new URL(fileUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
}
httpConn.disconnect();
  1. 使用Apache HttpClient庫下載文件:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(fileUrl);
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
FileOutputStream outputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
}
httpClient.close();
response.close();
  1. 使用Java NIO下載文件:
URL url = new URL(fileUrl);
ReadableByteChannel channel = Channels.newChannel(url.openStream());
FileOutputStream outputStream = new FileOutputStream(savePath);
outputStream.getChannel().transferFrom(channel, 0, Long.MAX_VALUE);
outputStream.close();
channel.close();
  1. 使用Java IO和BufferedStream下載文件:
URL url = new URL(fileUrl);
BufferedInputStream inputStream = new BufferedInputStream(url.openStream());
FileOutputStream outputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
  1. 使用Apache Commons IO庫下載文件:
URL url = new URL(fileUrl);
FileUtils.copyURLToFile(url, new File(savePath));

請注意,以上代碼可能需要處理異常或添加進一步的邏輯來完善下載過程。

0
饶平县| 界首市| 蒙自县| 麻栗坡县| 东兴市| 宁晋县| 博客| 巩义市| 阿拉善右旗| 朔州市| 石渠县| 冀州市| 常山县| 洞口县| 从江县| 海原县| 临夏县| 施甸县| 吴忠市| 巩留县| 台江县| 若尔盖县| 宣威市| 红桥区| 景东| 喜德县| 三门峡市| 磐安县| 翼城县| 吉木乃县| 南澳县| 桦川县| 财经| 淅川县| 清水河县| 和政县| 修水县| 玛纳斯县| 淮阳县| 喜德县| 新源县|