/*
*该程序采用10线程控制下载,速度大大提升
*目前支持http协议下载
*切换到文件所在目录中
*在命令行中输入java Download5 http://...,回车,即可运行程序
*/
import java.io.*;
import java.net.*;
public class Download5 extends Thread
{
private long start;
private long end;
private String urls,name;
private int ID;
public Download5(String urls,String name,int ID,long start,long end)
{
this.start=start;
this.end=end;
this.urls=urls;
this.ID=ID;
this.name=name;
}
public void run()
{
try
{
System.out.println("线程"+ID+"启动...");
File file=new File(name);
URL url=new URL(urls);
URLConnection con=url.openConnection();
con.setAllowUserInteraction(true);
con.setRequestProperty("Range","bytes="+start+"-"+end);
RandomAccessFile rand=new RandomAccessFile(file,"rw");
rand.seek(start);
byte[] b=new byte[2048];
BufferedInputStream buffer=new BufferedInputStream(con.getInputStream());
int n=0;
while((n=buffer.read(b,0,b.length))!=-1)
{
rand.write(b,0,n);
}
System.out.println("线程"+ID+"下载完毕");
buffer.close();
rand.close();
this.interrupt();
}
catch(Exception ee)
{
ee.printStackTrace();
}
}
public static void main(String[] args)
{
String urls=args[0];
int u=urls.lastIndexOf(’/’);
String name=urls.substring(u+1,urls.length());
try
{
long time=System.currentTimeMillis()/1000;
URL url=new URL(urls);
URLConnection con=url.openConnection();
int filelength=con.getContentLength();
int num=10;
int size=filelength/num;
Download5 t=null;
CountTime count=new CountTime(urls,name,time);
count.start();
for(int i=0;i<num;i++)
{
if(i!=num-1)
{
t=new Download5(urls,name,i+1,size*i,size*(i+1)-1);
t.start();
}
else
{
t=new Download5(urls,name,i+1,size*i,filelength);
t.start();
}
}
}
catch(Exception ee)
{
ee.printStackTrace();
}
}
}
class CountTime extends Thread
{
private String urls,name;
private long time;
public CountTime(String urls,String name,long time)
{
this.urls=urls;
this.name=name;
this.time=time;
}
public void run()
{
try
{
URL url=new URL(urls);
URLConnection con=url.openConnection();
int filelength=con.getContentLength();
File f=new File(name);
while(f.length()<filelength)
{
long LEN=f.length();
this.sleep(1000);
System.out.println((f.length()-LEN)/1024/1.0+"kb/s");
}
System.out.println("文件下载完毕");
System.out.println("下载所用总时间: "+(System.currentTimeMillis()/1000-time)+"s");
this.interrupt();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
3COME考试频道为您精心整理,希望对您有所帮助,更多信息在http://www.reader8.com/exam/