〖JAVA经验〗JAVA技巧:命令行多线程下载源代码共享

/*

*该程序采用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();

}

}

}

一起交流学习请访问:Tore_m_1206686_21115_1_1.html”>http://www.shangxueba.com/sTore_m_1206686_21115_1_1.html

怠惰是贫穷的制造厂。

〖JAVA经验〗JAVA技巧:命令行多线程下载源代码共享

相关文章:

你感兴趣的文章:

标签云: