首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

JAVA中HTTP的多线程上载程序

2012-11-12 
JAVA中HTTP的多线程下载程序public?class?DownloadNetTest?{?????private?File?fileOut?????private?URL?

JAVA中HTTP的多线程下载程序

  1. public?class?DownloadNetTest?{?????private?File?fileOut;??
  2. ???private?URL?url;?????private?long?fileLength=0;??
  3. ???//初始化线程数?????private?int?ThreadNum=5;??
  4. ???public?DownloadNetTest(){?????try{??
  5. ??????System.out.println("正在链接URL");????????url=new?URL("http://211.64.201.201/uploadfile/nyz.mp3");??
  6. ??????HttpURLConnection?urlcon=(HttpURLConnection)url.openConnection();????????fileLength=urlcon.getContentLength();??
  7. ??????if(urlcon.getResponseCode()>=400){????????System.out.println("服务器响应错误");??
  8. ??????System.exit(-1);????????}??
  9. ??????if(fileLength<=0)????????System.out.println("无法获知文件大小");??
  10. ??????//打印信息????????printMIME(urlcon);??
  11. ??????System.out.println("文件大小为"+fileLength/1024+"K");????????//获取文件名??
  12. ??????String?trueurl=urlcon.getURL().toString();????????String?filename=trueurl.substring(trueurl.lastIndexOf('/')+1);??
  13. ??????fileOut=new?File("D://",filename);?????}??
  14. ???catch(MalformedURLException?e){????????System.err.println(e);??
  15. ???}?????catch(IOException?e){??
  16. ??????System.err.println(e);?????}??
  17. ???init();??}??
  18. ???private?void?init(){????????DownloadNetThread?[]?down=new?DownloadNetThread[ThreadNum];??
  19. ???try?{????????for(int?i=0;i<ThreadNum;i++){??
  20. ?????????RandomAccessFile?randOut=new?RandomAccessFile(fileOut,"rw");???????????randOut.setLength(fileLength);??
  21. ?????????long?block=fileLength/ThreadNum+1;???????????randOut.seek(block*i);??
  22. ?????????down[i]=new?DownloadNetThread(url,randOut,block,i+1);???????????down[i].setPriority(7);??
  23. ?????????down[i].start();????????}??
  24. ???//循环判断是否下载完毕?????boolean?flag=true;??
  25. ???while?(flag)?{????????Thread.sleep(500);??
  26. ??????flag?=?false;????????for?(int?i?=?0;?i?<?ThreadNum;?i++)??
  27. ??????if?(!down[i].isFinished())?{????????flag?=?true;??
  28. ??????break;????????}??
  29. ??}//?end?while?????System.out.println("文件下载完毕,保存在"+fileOut.getPath()?);??
  30. ???}?catch?(FileNotFoundException?e)?{???????????System.err.println(e);??
  31. ?????????e.printStackTrace();?????}??
  32. ???catch(IOException?e){????????System.err.println(e);??
  33. ??????e.printStackTrace();?????}??
  34. ???catch?(InterruptedException?e)?{?????System.err.println(e);??
  35. ???}??}??
  36. private?void?printMIME(HttpURLConnection?http){?????for(int?i=0;;i++){??
  37. ???String?mine=http.getHeaderField(i);?????if(mine==null)??
  38. ???return;?????System.out.println(http.getHeaderFieldKey(i)+":"+mine);??
  39. ???}??}??
  40. public?static?void?main(String[]?args)?{?????????DownloadNetTest?app=new?DownloadNetTest();??
  41. }??}??

http://www.xiangw.com

热点排行