温馨提示×

java实现文件下载的方式有哪些

小亿
96
2024-04-08 10:21:39
栏目: 编程语言

在Java中,可以使用以下方式实现文件下载:

  1. 使用URL和URLConnection类:可以通过创建URL对象,然后打开连接并获取输入流,将输入流写入输出流实现文件下载。
URL url = new URL(fileUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpConn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(localFilePath);

int bytesRead;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, bytesRead);
}

outputStream.close();
inputStream.close();
  1. 使用Apache HttpClient库:可以使用HttpClient库来简化文件下载过程,通过HttpGet请求获取文件内容并保存到本地文件。
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();
    FileOutputStream outputStream = new FileOutputStream(localFilePath);

    int bytesRead;
    byte[] buffer = new byte[4096];
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }

    outputStream.close();
    inputStream.close();
}

httpClient.close();
  1. 使用Files类:Java 7引入了Files类,可以使用它的copy()方法实现文件的下载。
URL url = new URL(fileUrl);
InputStream inputStream = url.openStream();
Files.copy(inputStream, Paths.get(localFilePath), StandardCopyOption.REPLACE_EXISTING);

这些方式都可以用来实现文件下载,可以根据具体需求选择合适的方式。

0