中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

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
丰顺县| 台山市| 石棉县| 荆门市| 沧源| 盐池县| 天津市| 黄陵县| 松潘县| 庄河市| 凤山市| 方正县| 炎陵县| 太谷县| 长汀县| 达孜县| 肇州县| 陆丰市| 梓潼县| 吉木萨尔县| 济南市| 武威市| 亚东县| 灵寿县| 香港| 河津市| 南投市| 通道| 石棉县| 会昌县| 奉贤区| 林芝县| 湖北省| 藁城市| 安阳市| 政和县| 敦煌市| 大石桥市| 温宿县| 西乌珠穆沁旗| 南投市|