模拟迅雷下载程序 多线程

废话少说上代码

package com.yc.net.http01;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.text.NumberFormat;
//加快下载速度使用多线程
//1.怎么拆分多段
//2.怎么进行 多段下载  ,使用请求报头   Range:bytes=开始字节位置-结束字节位置
//3.多段下载后合并 的结果  使用随机存储流    RandomAccessFile进行合并
public class XueLei02 {
    public static void main(String[] args) {
        try {
            XueLei02 x1=new XueLei02();
            URL url=new URL("http://dlsw.baidu.com/sw-search-sp/soft/ca/13442/Thunder_dl_7.9.41.5020_setup.1444900082.exe");
            int threadSize=5;//线程数
            //1.怎么拆分多段
            final long totalSize=x1.getTotalLength(url, threadSize);
            Long perLength=totalSize %threadSize==0 ?totalSize/threadSize :(totalSize/threadSize +1);
            
            String path="d:\\Thunder04"+System.currentTimeMillis()+".exe";
            long freeSpace =getFileFreeSpace(path);
            if(totalSize>=freeSpace-1024L*1024*1024*86){//判断下载空间是否充足
                System.out.println("可用空间不足,请清理磁盘后再下载。。。。");
                return;//不继续向下执行
            }

            //监听下载文件大小的对象
            CountDownloadSizeListener cds1=new CountDownloadSizeListener(){
                long dowmloadSize=0;
                @Override
                public void CountSize(int size) {
                    dowmloadSize+=size;//统计每一次下载文件的大小
                    //下载的百分比
                    double percent=dowmloadSize *1.0/totalSize;
                    //获得百分比格式化对象
                    NumberFormat nf=NumberFormat.getPercentInstance();
                    nf.setMinimumFractionDigits(2);
                    System.out.println("下载进度:"+nf.format(percent));
                }
            };
            for(int i=0;i<5;i++){
                new DownloadFile(url,i,perLength,path,cds1).start();
            }
            
        
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //取到文件所在目录的可用空间
private static long getFileFreeSpace(String path) {
        File f=new File(path);
        File parentFile=f.getParentFile();//取得文件目录
        return parentFile.getFreeSpace();//取到目录的可用空间大小
    }
//取到每个线程下载的长度
private  Long getTotalLength(URL url,int threadSize) {
        
        try {
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("HEAD");
                long totalSize=con.getContentLengthLong();
                System.out.println(totalSize+"=="+con.getContentLength());
                return totalSize;
        } catch (ProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}
class DownloadFile extends Thread{
    
    private URL url;//下载地址
    private int threadId;//下载标号
    private long threadFileSize;//线程文件的下载长度
    private String path;//合并的文件
    private CountDownloadSizeListener cds1;
    
    public DownloadFile( URL url, int threadId,
            long threadFileSize, String path,CountDownloadSizeListener cds1) {
        super();
        
        this.url = url;
        this.threadId = threadId;
        this.threadFileSize = threadFileSize;
        this.path = path;
        this.cds1=cds1;
    }
    public void run(){
        //请求
        try {
            HttpURLConnection con=(HttpURLConnection) url.openConnection();//获得连接对象
//    con.setRequestMethod("HEAD");   //设置请求方式   head get post.....
            con.setRequestMethod("GET");
            long start=threadId *threadFileSize;
            long end=(threadId+1)*threadFileSize-1;
            con.setRequestProperty("Range", "bytes="+start+"-"+end);
            con.setConnectTimeout(10000);
            InputStream in=con.getInputStream();
            RandomAccessFile raf=new RandomAccessFile(path,"rwd");
            byte[] bs=new byte[1024*1024];
            int length=0;
            raf.seek(start);
            while((length=in.read(bs))!=-1){
                raf.write(bs,0,length);
                cds1.CountSize(length);
            }
            in.close();
            raf.close();
            System.out.println("第"+threadId+"个线程下载成");
        } catch (ProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}
说明是英文的,不过软件安装完是中文界面的。 到http://www.metaproducts.com/mp/metaproducts_download_express.htm 这里可以下载 --------------------------------------- MetaProducts Download Express 1.9 MetaProducts Download Express is free for non-commercial use. If you want to use it for commercial purposes, or just obtain the advanced features available in the registerable version, then please purchase a license. Click here to read about the Advanced Features. MetaProducts Download Express is a Windows 95/98/NT/2000/ME/XP/2003 program that allows you to download individual files from the Web and FTP sites at the maximum possible speed. Multiple channels technology significantly reduces download time. MetaProducts Download Express is a small (about 680 Kb) application. Currently it supports Microsoft Internet Explorer and Mozilla FireFox browsers. MetaProducts Download Express has the auto-learn feature. It will ask you about including filename extensions when you add files with a new extension using browser click hot keys. When you cancel, MetaProducts Download Express opens a file window for unwanted file types and asks if you want to exclude this extension from its file types list. Internet Explorer clicks monitoring hot keys: - Please hold the Alt+Control keys down when clicking to add any link to MetaProducts Download Express; - Please hold the Shift key down when clicking to have MetaProducts Download Express ignore a link. Mozilla FireFox 1.x - 2.x, Netscape 8.x, SeaMonkey, Flock browsers plug-in Click here to download MetaProducts Integration plug-in for Mozilla FireFox and Netscape browsers. Please use the following link to download add-on for the old FireFox (1.x - 2.x) version: old version. To install the plug-in, please drag and drop the file to FireFox browser window using Windows Explorer. Then please restart FireFox. Now you can use the link right-click menu item "Download Express: download this file." Also, FireFox will offer you to use Download Express to download files. --------------------------------------------------------------------------------
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wen's

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值