zoukankan      html  css  js  c++  java
  • 通过HttpUrlConnection下载文件并显示进度条

    实现效果:

    核心下载块:


    int count = 0;
    URL url = new URL("http://hezuo.downxunlei.com/xunlei_hezuo/thunder(127891).exe");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();//建立连接
     
    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    }else return;

    totalSize = connection.getContentLength();//获取文件总大小

    InputStream is = connection.getInputStream();
    OutputStream os = new FileOutputStream(
    Environment.getExternalStorageDirectory() + "/download.exe");
    int len=0;

    bar.setMax(totalSize);//设置进度条最大长度
    Log.i("xiaohong", "max" + bar.getMax());

    byte bs[] = new byte[1024];
    while ((len = is.read(bs)) != -1) {
    os.write(bs, 0, len);//写入文件
    count += len;handler.sendEmptyMessage(count);

    }
    os.flush();
    is.close();
    os.close();//最后关闭输入输出流

    //设置进度条及文本

    final Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
    // TODO Auto-generated method stub
    super.handleMessage(msg);
    bar.setProgress(msg.what);
    textView.setText("进度" + String.format("%.1f", msg.what * 1f / totalSize * 100) + "%");//保留一位小数点,且需注意数据在计算时应转为浮点型!
    }
    };

  • 相关阅读:
    ArrayList源码解析
    Oracle WITH A AS 用法解析
    oracle关于时间分区的查询
    request.getRealPath("/")
    Oracle部分sql优化
    Java虚拟机
    java谜题-表达式谜题
    java和oracle简单的日期格式化
    java编译后在tomcat下无class文件
    JSP 中文乱码及其解决方案
  • 原文地址:https://www.cnblogs.com/lzh-Linux/p/4983977.html
Copyright © 2011-2022 走看看