这段代码是一个方法,用来从指定的 URL 下载文件并保存到指定的文件路径中。

  1. 首先,通过传入的 urlStr 和 filePath 参数创建一个 URL 对象和一个 HttpURLConnection 对象。
  2. 设置连接超时时间、设置是否允许输入输出、设置缓存使用情况、设置请求方法和请求属性等。
  3. 调用 connect() 方法与服务器建立连接。
  4. 使用 httpUrlConnection.getInputStream() 方法获取服务器返回的输入流。
  5. 创建一个临时字节数组 temp,并使用循环从输入流中读取数据,并将读取到的数据写入到文件输出流 fos 中。
  6. 最后,在 finally 块中关闭输入流、输出流和 HttpURLConnection 连接。

这段代码的作用是将从指定 URL 下载的文件保存到指定的文件路径中。

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();
            }
        }
    }

这段代码示例展示了使用 HttpURLConnection 类从指定 URL 下载文件并保存到本地文件系统的基本流程。代码中使用了 try-catch-finally 块来处理异常,并在 finally 块中关闭了连接和流,以避免资源泄漏。


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

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