博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java 仿迅雷多线程下载
阅读量:6000 次
发布时间:2019-06-20

本文共 5493 字,大约阅读时间需要 18 分钟。

package net.webjoy.jackluo.android_json;/** *  1.http Range "bytes="+  start+end *  2.RandomAccessFile设置写入的位置 *  3开启多线程下载 * * Created by jackluo on 9/30/15. */import android.os.Environment;import android.os.Handler;import android.os.Message;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.util.concurrent.Executor;import java.util.concurrent.Executors;/** * 多线程下载 */public class DownLoad {    //创建一个线程池      创建三个线程    private Executor threadPool = Executors.newFixedThreadPool(3);    private Handler handler;    public DownLoad(Handler handler){        this.handler = handler;    }    //创建一个线程池对象    static class DownLoadRunnable implements Runnable{        private String url;        private String fileName;        private long start ;//开始位置        private long end;//结束位置        private Handler handler;        public DownLoadRunnable(String url,String fileName,long start,long end,Handler handler){            this.url = url;            this.fileName = fileName;            this.start = start;            this.end = end;            this.handler = handler;        }        @Override        public void run() {            try {                URL httpUrl = new URL(url);                HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();                connection.setRequestMethod("GET");                connection.setReadTimeout(5000);                //设置下载位置  向服务器拿到指定的流信息                connection.setRequestProperty("Range", "bytes=" + start + "-" + end);                //创建一个文件  根据指定位置写入信息                RandomAccessFile accessFile = new RandomAccessFile(new File(fileName),"rwx");                accessFile.seek(start);//设置读写的位置                InputStream inputStream = connection.getInputStream();                byte[] b = new byte[1024*4];//设置缓冲区的大小存                int len=0;                while ((len = inputStream.read(b))!=-1){                    accessFile.write(b,0,len);                }                if (accessFile !=null){                    accessFile.close();                }                if (inputStream !=null){                    inputStream.close();                }                //给主线程发送一个消息                Message message = new Message();                message.what = 1;                handler.sendMessage(message);            } catch (MalformedURLException e) {                e.printStackTrace();            } catch (IOException e) {                e.printStackTrace();            }        }    }    public void downLoadFile(String url){        try {            URL httpUrl = new URL(url);            HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();            connection.setRequestMethod("GET");            connection.setReadTimeout(5000);            int count = connection.getContentLength();//获取了图片的大小            int block = count/3;            //算线程的启始位置            String fileName = getFileName(url);            File parent = Environment.getExternalStorageDirectory();            File fileDownLoad = new File(parent,fileName);            /**             * 11 / 3 = 每个下载 3个字节3 还余出2个字节空间             * 第一个线程 0-2             * 第二个线程 3-5             * 第三个线程 6-10             *             *             */            for (int i=0;i<3;i++){                long start = i*block;                long end = (i+1)*block -1;                if (i==2){                    end = count;                }                DownLoadRunnable runnable = new DownLoadRunnable(url, fileDownLoad.getAbsolutePath(),start,end,handler);                //提交任务                threadPool.execute(runnable);            }        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }    /**     * 获取 URL后缀名     */    public String getFileName(String url){        return url.substring(url.lastIndexOf("/")+1);    }}
package net.webjoy.jackluo.android_json;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.TextView;public class DownLoadActivity extends AppCompatActivity {    private Button button;    private TextView textView;    private int count =1;    private Handler handler = new Handler(){        @Override        public void handleMessage(Message msg) {            //super.handleMessage(msg);            int result = msg.what;            count +=result;            if (count==3){                textView.setText("download success");            }        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_down_load);        button = (Button) findViewById(R.id.downlad_btn);        textView = (TextView) findViewById(R.id.textView);        button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                new Thread(){                    @Override                    public void run() {                        DownLoad load = new DownLoad(handler);                        load.downLoadFile("http://news.jsyks.com/photo/img1a.xgo-img.com.cn/pics/737/736406.jpg");                    }                }.start();            }        });    }}

 

转载地址:http://hikmx.baihongyu.com/

你可能感兴趣的文章
lvreduce -L 1000M /dev/vg0/lv0 表示最后缩减至多大,不是减少了多大
查看>>
ES 自动恢复分片的时候不恢复了是磁盘超过了85%,然后不恢复了 ES可以配置多个数据目录...
查看>>
linux查杀病毒的几个思路
查看>>
宽带速度
查看>>
构建之法阅读笔记5
查看>>
Android判断网络连接状态
查看>>
leetcode_1033. Moving Stones Until Consecutive
查看>>
logback logback.xml常用配置详解(二)<appender>
查看>>
js常用的函数库
查看>>
Sqlserver 数据库安全
查看>>
netstat命令简单使用
查看>>
Python标示符命名规则
查看>>
SSL certificate problem unable to get local issuer certificate解决办法
查看>>
20145209 刘一阳 《网络对抗》实验四:恶意代码分析
查看>>
个人学期总结
查看>>
CodeForces 985E Pencils and Boxes
查看>>
为什么Elasticsearch查询变得这么慢了?
查看>>
Cetos 中添加bbr服务
查看>>
win7_64位操作系统安装python3.6.3遇到的问题和解决方法
查看>>
html5笔记
查看>>