Java多线程下载

来源:互联网 发布:applem2传奇引擎源码 编辑:程序博客网 时间:2024/06/05 23:43
通过多线程对文件分段进行下载,废话不多说,直接上代码
package com.download.test; import java.io.File;import java.net.HttpURLConnection;import java.net.URL;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors; /* * 多线程下载 */public class DownloadTest {    //初始一个带缓存的线程池    public static ExecutorService executorService = Executors.newCachedThreadPool();    public static void main(String[] args) throws Exception {        String path = "http://csdn-app.csdn.net/csdn.apk";        new DownloadTest().download(path,3);    }         public void download (String path,int threadsize) throws Exception{        URL url = new URL(path);        HttpURLConnection conn = (HttpURLConnection) url.openConnection();        conn.setConnectTimeout(3000);        conn.setRequestMethod("GET");        if(conn.getResponseCode() == 200){            //获取网络文件长度,文件的大小(单位是字节)            int length = conn.getContentLength();               //新建本地文件保存下载数据            File file = new File("D:/"+getFilename(path));            //计算每条线程负责下载的数据量            int block = length%threadsize==0 ? length/threadsize : length/threadsize+1;            //开启指定数目的线程同时下载            for(int threadid = 0; threadid < threadsize; threadid++){            executorService.execute(new DownloadThread(threadid,block,url,file,length));                //new DownloadThread(threadid,block,url,file,length).start();            }        }else{            System.out.println("下载失败!");        }    }         private String getFilename(String path) {        return path.substring(path.lastIndexOf("/")+1);    }}


下载线程类

package com.download.test;import java.io.File;import java.io.InputStream;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.URL;public class DownloadThread extends Thread{private static int finished;    private int threadid;   //线程编号    private int block;      //下载块大小    private URL url;        //下载链接    private File file;      //下载数据保存文件    private int length;//文件长度        public DownloadThread(int threadid, int block, URL url, File file,int length) {        this.threadid = threadid;        this.block = block;        this.url = url;        this.file = file;        this.length = length;    }    public void run() {        int start = threadid * block;       //本线程下载数据写入文件开始位置        int end = (threadid+1) * block - 1; //本线程下载数据写入文件结束位置        try {            //创建一个随机访问文件流对象            RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");            //文件指针偏移至正确写入位置            accessFile.seek(start);            HttpURLConnection conn = (HttpURLConnection) url.openConnection();            conn.setConnectTimeout(3000);            conn.setRequestMethod("GET");            //设置请求数据的范围            conn.setRequestProperty("Range", "bytes="+start+"-"+end);            if(conn.getResponseCode() == 206){//状态码206:(部分内容) 服务器成功处理了部分 GET 请求                InputStream inStream = conn.getInputStream();                long time = System.currentTimeMillis();                byte[] buffer = new byte[1024];                int len = 0;                while((len = inStream.read(buffer)) != -1){                    accessFile.write(buffer, 0, len);                    finished += len;                    int i = finished * 100 / length;                    //System.out.println(finished+"----------"+length);                    if(System.currentTimeMillis()-time>500 || finished>=length){                    time = System.currentTimeMillis();                    System.out.println("下载进度:"+i+"%");                    }                }                accessFile.close();                inStream.close();            }            System.out.println("第"+(threadid+1)+"部分下载完成");        } catch (Exception e) {            e.printStackTrace();        }    }}



0 0
原创粉丝点击