旅人葉 2017-01-20 02:28 采纳率: 100%
浏览 971

HttpURLConnection相关,求解释,,

前任的代码,没有注释解说,没有文档,以前没用过这种方式,只能慢慢测试,然而项目着急,哪位大神有时间指导一下,大概的工作原理就行,,,

 public static void downloadFile(String fileUrl, String localFile)
throws java.io.IOException {
java.io.FileOutputStream fos = null;
java.io.BufferedInputStream bis = null;
try {
bis = getstream(fileUrl);
java.io.File file_in = new java.io.File(localFile);
fos = new java.io.FileOutputStream(file_in);
byte[] bytes = new byte[4096];
int c;
while ((c = bis.read(bytes)) != -1) {
fos.write(bytes, 0, c);
}
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (Exception e) {

            }
        }
    }
}
private static java.io.BufferedInputStream getstream(String fileUrl)
throws java.io.IOException {
java.io.BufferedInputStream bis;
java.net.URL url1 = new java.net.URL(fileUrl);
java.net.HttpURLConnection huc = (java.net.HttpURLConnection) url1
.openConnection();
bis = new java.io.BufferedInputStream(huc.getInputStream());
return bis;
}
  • 写回答

2条回答 默认 最新

  • XL_Leon 2017-01-20 03:12
    关注

    public static void downloadFile(String fileUrl, String localFile)
    throws java.io.IOException {
    // 以流的形式下载文件。
    java.io.FileOutputStream fos = null;
    java.io.BufferedInputStream bis = null;
    try {
    //获取下载流
    bis = getstream(fileUrl);
    java.io.File file_in = new java.io.File(localFile);
    // 读到流中
    fos = new java.io.FileOutputStream(file_in);
    byte[] bytes = new byte[4096];
    int c;
    // 循环取出流中的数据
    while ((c = bis.read(bytes)) != -1) {
    fos.write(bytes, 0, c);
    }
    } finally {
    if (fos != null) {
    try {
    fos.close();
    } catch (Exception e) {
    }
    }
    if (bis != null) {
    try {
    bis.close();
    } catch (Exception e) {

            }
        }
    }
    

    }
    private static java.io.BufferedInputStream getstream(String fileUrl)
    throws java.io.IOException {
    java.io.BufferedInputStream bis;
    java.net.URL url1 = new java.net.URL(fileUrl);
    java.net.HttpURLConnection huc = (java.net.HttpURLConnection) url1
    .openConnection();
    bis = new java.io.BufferedInputStream(huc.getInputStream());
    return bis;
    }

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog