亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

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
商都县| 海林市| 油尖旺区| 来安县| 宿迁市| 焉耆| 鄂温| 威远县| 博爱县| 阿拉善左旗| 康乐县| 娄底市| 交口县| 汉源县| 孟村| 云和县| 都江堰市| 怀远县| 龙陵县| 青海省| 赣榆县| 荥经县| 蓬溪县| 海晏县| 贺州市| 七台河市| 云南省| 罗江县| 岗巴县| 江达县| 旺苍县| 获嘉县| 扶余县| 杨浦区| 张家川| 东兰县| 边坝县| 明光市| 龙陵县| 商河县| 山丹县|