温馨提示×

java下载文件到本地的方法有哪些

小亿
557
2023-07-26 23:00:57
栏目: 编程语言

在Java中,下载文件到本地的方法有多种。以下是一些常用的方法:

  1. 使用URL和URLConnection类下载文件:
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
OutputStream outputStream = new FileOutputStream(localFilePath);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
  1. 使用HttpClient库下载文件:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(fileUrl);
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
OutputStream outputStream = new FileOutputStream(localFilePath);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
}
response.close();
httpClient.close();
  1. 使用Java NIO下载文件:
URL website = new URL(fileUrl);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(localFilePath);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();

这些方法都可以将远程文件下载到本地指定的文件路径中。具体方法的选择取决于你的需求和项目中使用的库。

0