当前位置:首页 » JAVA技术教程

Java多线程下载

2008-06-09 17:27 本站整理 浏览(15)
同时下载多个文件,不过单文件没有多线程的下载并且没有断点续传功能,继续完善:
packagecom.util.file;

publicclassFiles{

/***
*获取应用程序的根目录
*@return应用程序根目录
*/
publicstaticStringgetSysPath(){
	returnSystem.getProperty("user.dir");
}


}
packagecom.core.crawl;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.net.HttpURLConnection;importjava.net.URL;importcom.core.http.Http;publicclassWebSpiderimplementsRunnable{privateHttphttp=newHttp();privateStringwebAddress="";privateStringdestFile="";publicvoidsetWebAddress(StringwebAddress){	this.webAddress=webAddress;}publicvoidsetDestFile(StringdestFile){	this.destFile=destFile;}publicbooleandownload()throwsIOException,InterruptedException{	HttpURLConnectionhttpConn=null;	try{	URLurl=newURL(webAddress);		httpConn=(HttpURLConnection)url.openConnection();	httpConn.setRequestMethod("GET");	httpConn.setRequestProperty("User-Agent","Mozilla/5.0(Windows;U;WindowsNT5.1;zh-CN;rv:1.8.1.14)Gecko/20080404Firefox/2.0.0.14");	InputStreamin=httpConn.getInputStream();	StringfileType=http.fileType(httpConn.getContentType());	System.out.println(fileType);	FileOutputStreamout=newFileOutputStream(newFile(destFile+fileType));	intchByte=in.read();	while(chByte!=-1){		out.write(chByte);		//System.out.println(chByte);		chByte=in.read();	}	}catch(Exceptionex){	System.out.println(ex.toString());	}finally{	httpConn.disconnect();	}	returntrue;}publicvoidrun(){	try{	//System.out.println(Thread.currentThread().getName());	download();	}catch(IOExceptione){	e.printStackTrace();	}catch(InterruptedExceptione){	e.printStackTrace();	}}}
packagecom.core.crawl;importjava.io.IOException;importcom.util.file.Files;publicclassCrawl{/***@paramargs*@throwsIOException*@throwsInterruptedException*/publicstaticvoidmain(String[]args)throwsIOException,InterruptedException{	longbegin=System.currentTimeMillis();	WebSpiderspider2=newWebSpider();	WebSpiderspider1=newWebSpider();	spider1.setWebAddress("http://www.163.com");	spider1.setDestFile(Files.getSysPath()+"/"+"spider1.");		spider2.setWebAddress("http://blog.csdn.net/longronglin");	spider2.setDestFile(Files.getSysPath()+"/"+"spider2.");	Threadt1=newThread(spider1);	Threadt2=newThread(spider2);	t1.start();	t2.start();	t1.join();	t2.join();		System.out.println("theend");	System.out.println(System.currentTimeMillis()-begin);}}
测试通过: