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) + "%");//保留一位小数点,且需注意数据在计算时应转为浮点型!
    }
    };

  • 相关阅读:
    bootstrap组件的案例代码
    bootstrap样式代码案例
    bootstrap组件
    bootstrap样式
    响应式布局
    使用java将字符串写入到指定的文件中
    使用java读取文件并输出
    使用java解析XML文件的步骤
    数据访问层
    Python:进程
  • 原文地址:https://www.cnblogs.com/lzh-Linux/p/4983977.html
Copyright © 2011-2022 走看看