这段代码是一个用于从指定URL下载文件的 Java 方法,名为 downloadFile()

方法参数:

  • urlStr (String): 文件的 URL 地址。
  • filePath (String): 希望保存文件的本地路径。

代码逻辑:

  1. 创建 URL 对象,并根据 URL 对象创建 HttpURLConnection 对象。
  2. 设置连接超时时间、允许输入输出、禁用缓存等属性。
  3. 设置请求方法为 HTTP_TYPE (可能是 GET 或 POST 等)。
  4. 设置请求字符集为 ENCODING_UTF_8
  5. 连接到指定的 URL。
  6. 获取输入流 fis,读取文件内容。
  7. 创建输出流 fos,并将文件内容写入指定的文件路径。
  8. 关闭输入流、输出流和 HTTP 连接。

代码示例:

private void downloadFile(String urlStr, String filePath) {
//  String urlStr = 'http://dwbillcenter.alipay.com/downloadBillFile.resource?bizType=X&userId=X&fileType=X&bizDates=X&downloadFileName=X&fileId=X';
//  String filePath = '/Users/fund_bill_20160405.zip';
  URL url = null;
  HttpURLConnection httpUrlConnection = null;
  InputStream fis = null;
  FileOutputStream fos = null;
  try {
    url = new URL(urlStr);
    httpUrlConnection = (HttpURLConnection) url.openConnection();
    httpUrlConnection.setConnectTimeout(DOWNLOD_CON_TIMEOUT);
    httpUrlConnection.setDoInput(true);
    httpUrlConnection.setDoOutput(true);
    httpUrlConnection.setUseCaches(false);
    httpUrlConnection.setRequestMethod(HTTP_TYPE);
    httpUrlConnection.setRequestProperty(HTTP_REQUEST_CHARSERT, ConCommConstant.ENCODING_UTF_8);
    httpUrlConnection.connect();
    fis = httpUrlConnection.getInputStream();
    byte[] temp = new byte[1024];
    int b;
    fos = new FileOutputStream(new File(filePath));
    while ((b = fis.read(temp)) != -1) {
      fos.write(temp, 0, b);
      fos.flush();
    }
  } catch (MalformedURLException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  } finally {
    try {
      if (fis != null) fis.close();
      if (fos != null) fos.close();
      if (httpUrlConnection != null) httpUrlConnection.disconnect();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

使用方法:

要使用 downloadFile() 方法,您需要将 URL 地址和目标文件路径作为参数传递给该方法。例如:

String url = 'http://example.com/file.zip';
String filePath = '/path/to/file.zip';

downloadFile(url, filePath);

这将从 http://example.com/file.zip 下载文件并将其保存到 /path/to/file.zip

注意:

  • DOWNLOD_CON_TIMEOUTHTTP_TYPEHTTP_REQUEST_CHARSERT 应该被替换为实际的常量值。
  • 该方法可能需要一些网络权限才能正常工作。
  • 下载大型文件可能会花费很长时间。
  • 如果您需要处理下载进度,可以在 while 循环中添加代码来更新进度条。

原文地址: https://www.cveoy.top/t/topic/o3px 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录