21xrx.com
2024-11-22 09:49:47 Friday
登录
文章检索 我的文章 写文章
《Java下载文件工具类:实现文件下载的利器》
2023-06-17 09:20:32 深夜i     --     --
Java 文件下载 URLConnection

Java编程中,文件下载是经常遇到的功能之一,而下载文件的方式有多种,如:使用URLConnection、HttpClient、OkHttp等第三方库。然而,在日常开发中,每次都需要写一遍下载文件的代码是一件非常麻烦的事情。为了避免重复造轮子,我们可以借助Java下载文件工具类,来实现文件下载的功能。

下面,我们以URLConnection为例,演示如何使用Java下载文件工具类:


import java.net.URL;

import java.io.IOException;

import java.io.InputStream;

import java.io.FileOutputStream;

import java.net.HttpURLConnection;

public class DownloadUtils {

  private static final int BUFFER_SIZE = 4096;

  public static void downloadFile(String fileURL, String saveDir)

      throws IOException {

    URL url = new URL(fileURL);

    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

    int responseCode = httpConn.getResponseCode();

    if (responseCode == HttpURLConnection.HTTP_OK) {

      String fileName = "";

      String disposition = httpConn.getHeaderField("Content-Disposition");

      if (disposition != null) {

        int index = disposition.indexOf("filename=");

        if (index > 0) {

          fileName = disposition.substring(index + 10,

              disposition.length() - 1);

        }

      } else {

        fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,

            fileURL.length());

      }

      InputStream inputStream = httpConn.getInputStream();

      String saveFilePath = saveDir + "\\" + fileName;

      FileOutputStream outputStream = new FileOutputStream(saveFilePath);

      int bytesRead = -1;

      byte[] buffer = new byte[BUFFER_SIZE];

      while ((bytesRead = inputStream.read(buffer)) != -1) {

        outputStream.write(buffer, 0, bytesRead);

      }

      outputStream.close();

      inputStream.close();

      System.out.println("File downloaded");

    } else {

      System.out.println("No file to download. Server replied HTTP code: " + responseCode);

    }

    httpConn.disconnect();

  }

}

在使用上述Java下载文件工具类时,只需要传入文件路径和保存路径,即可完成下载文件的过程。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复