课件课后练习代码-经典案例_第1页
课件课后练习代码-经典案例_第2页
课件课后练习代码-经典案例_第3页
课件课后练习代码-经典案例_第4页
课件课后练习代码-经典案例_第5页
免费预览已结束,剩余53页可下载查看

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

JavaSE02断点续传工具——DownloadInfo类编写以及TestHttpDownloadtestHttpDownload1方断点续传工具——DownloadInfo序列断点续 工具——DownloadInfo的fetchFileSize方法DownloadThread断点续 工具——完成DownloadFrame的UI及DownloadItem内部 多个文件,的过程中可以临时终止,可以随时继续 图-图-图-图-图-图-

图-图-可以多个要的文件,同时,如图-9所示图-privateStringprivatelongpos;privatelongfileSize;privateStringDownloadInfoinfo=newURLurl=newHttpURLConnectioncon=(HttpURLConnection)url.openConnection();InputStreamis=con.getInputStream();RandomAccessFileraf=newbyte[]buffer=newbyte[BUFFER_SIZE];intb=-1;while((b=is.read(buffer))!=-{raf.write(buffer,0,b);info.setPos(info.getPos()+b);}publicclassDownloadInfoprivateStringprivatelongprivatelongprivateStringfileName;publicDownloadInfo(Stringurl,StringfileName)this.url=this.fileName= publicStringgetUrl()return publicvoidsetUrl(Stringurl)this.url= publiclonggetPos()return publicvoidsetPos(longpos)this.pos= publicStringgetFileName()return publicvoidsetFileName(StringfileName)this.fileName= publiclonggetFileSize()return publicvoidsetFileSize(longfileSize)this.fileSize= }}publicvoidtestHttpDownload1()intBUFFER_SIZE=1024*tryDownloadInfoinfo= URLurl=newHttpURLConnectioncon=(HttpURLConnection)Stringprop="bytes="+info.getPos()+"-con.setRequestProperty("RANGE",InputStreamis=RandomAccessFilerafnewbyte[]buffer=newintb=-while((b=is.read(buffer))!=-1)raf.write(buffer,0,info.setPos(info.getPos()+ }catch(Exceptione) }publicvoidtestHttpDownload2()intBUFFER_SIZE=1024*tryDownloadInfoinfo= URLURLurl=newHttpURLConnectioncon=Stringprop="bytes="+con.setRequestProperty("RANGE",InputStreamis=RandomAccessFileraf/2+"-byte[]buffer=newintb=-while((b=is.read(buffer))!=-1)raf.write(buffer,0,info.setPos(info.getPos()+ }catch(Exceptione) }publicclassTestHttpDownloadpublicvoid{intBUFFER_SIZE=1024*tryDownloadInfoinfo=new URLurl=newHttpURLConnectioncon=(HttpURLConnection)Stringprop="bytes="+info.getPos()+"-con.setRequestProperty("RANGE",InputStreamis=RandomAccessFilerafnewbyte[]buffer=newintb=-while((b=is.read(buffer))!=-1)raf.write(buffer,0,info.setPos(info.getPos()+ }catch(Exceptione) }publicvoidtestHttpDownload2()intBUFFER_SIZE=1024*tryDownloadInfoinfo=newURLurl=newHttpURLConnectioncon=(HttpURLConnection)Stringprop="bytes="+info.getFileSize()/2+"-con.setRequestProperty("RANGE",InputStreamis=RandomAccessFilerafnewbyte[]buffer=newbyte[BUFFER_SIZE];intb=-1;while((b=is.read(buffer))!=-1){raf.write(buffer,0,b);info.setPos(info.getPos()+b);}}catch(Exceptione){}}}使DwnlaInf类的对象可序列化,并测试是否能将DonloaInf类的对象序列化到本地文件,并从本地文件反序列化出DonloaInf类的对象。publicclassDownloadInfoimplementsSerializable类的ObjectOutputStreamoos=ObjectOutputStream(newFileOutputStream(tmpFile));ObjectInputStreamois=newObjectInputStream(newDownloadInfoinfo=(DownloadInfo)publicclassDownloadInfoimplementsSerializableprivatestaticfinallongserialVersionUID=privateStringprivatelongprivatelongprivateStringpublicDownloadInfo(Stringurl,StringfileName)this.url=this.fileName= publicStringgetUrl()return publicvoidsetUrl(Stringurl)this.url= publiclonggetPos()return publicvoidsetPos(longpos)this.pos= publicStringgetFileName()return publicvoidsetFileName(StringfileName)this.fileName= publiclonggetFileSize()return}publicvoidsetFileSize(long{this.fileSize=}publicStringtoString()return"DownloadInfo[url="+url+",pos="+pos+",+fileSize+",fileName="+fileName+}}publicclassTestDownloadInfopublicvoid{tryDownloadInfoinfo=newDownloadInfo("FiletmpFile=newFile("obj.tmp");ObjectOutputStreamoos=newObjectOutputStream(new.}catch(ExceptionpublicvoidtestDeserializeObj(){; }tryFiletmpFile=newFile("obj.tmp");ObjectInputStreamois=newObjectInputStream(newDownloadInfoinfo=(DownloadInfo)}catch(Exceptione)}}}publicvoid{tryList<DownloadInfo>infoList=newArrayList<DownloadInfo>();DownloadInfoinfo1=newDownloadInfo("DownloadInfoinfo2=DownloadInfo(",DownloadInfoinfo3=newDownloadInfo(" }new}catch(Exceptione)publicvoid{tryFiletmpFile=newObjectInputStreamois=newObjectInputStream(newFileInputStrList<DownloadInfo>infoList=}catch(Exception{; }publicclassTestDownloadInfopublicvoid{tryDownloadInfoinfo=newDownloadInfo(".FiletmpFile=newObjectOutputStreamoos=newnew}catch(Exceptione)}}publicvoidtestDeserializeObj()tryFiletmpFile=newObjectInputStreamoisObjectInputStream(newDownloadInfoinfo=(DownloadInfo)}catch(Exceptione)}}publicvoidtestSerializeList()tryList<DownloadInfo>infoList=newDownloadInfoinfo1=new ",DownloadInfoinfo2=new"",DownloadInfoinfo3=new ",FiletmpFile=newObjectOutputStreamoos=newnew}catch(Exceptione) publicvoidtestDeserializeList()tryFiletmpFile=newObjectInputStreamois=newObjectInputStream(newList<DownloadInfo>infoList=}catch(Exceptione)}}HttpURLConntection类的getResponseCode获取HTTP*获取 *@returnprivateint{intfileSize=-1;try{URLurl=newHttpURLConnectionconn=(HttpURLConnection)url.openConnectionintstateCode=conn.getResponseCode();if(stateCode=={fileSize=conn.getContentLength();returnfileSize;}}catch(MalformedURLException{}catch(IOException{}return}创建DonloaTha类,使其继承Thad类,覆盖un方法来实现线程体,程体中实现文件其中用DnlaInf类的p属性记录文件的位置。publicvoidrun()while(!isStop()&&{tryURLurl=newURL(info.getUrl());HttpURLConnectioncon=(HttpURLConnection)url Stringprop="bytes="+info.getPos()+"- con.setRequestProperty("RANGE", InputStreamis= raf=newRandomAccessFile(info.getFileName(), byte[]buffer=new intb=- while((b=is.read(buffer))!=-1&&!isStop()) raf.write(buffer,0, info.setPos(info.getPos()+ intpercent=(int)(100*info.getPos()/ System.out.println(info.getFileName()+"已 +percent+ if(!isStop())isFinish=}}catch{}catch(IOExceptione)}finallytry}catch(IOExceptione)}}}}publicclassDownloadInfoimplementsSerializableprivatestaticfinallongserialVersionUID=privateStringprivatelongprivatelongprivateStringpublicDownloadInfo(Stringurl,StringfileName)this.url=this.fileName=this.fileSize=}publicStringgetUrl()return}publicvoidsetUrl(Stringurl)this.url=}publiclonggetPos()return}publicvoidsetPos(longpos)this.pos=}publicStringgetFileName()return}publicvoidsetFileName(StringfileName)this.fileName=}publiclonggetFileSize()return}publicvoidsetFileSize(longfileSize)this.fileSize=}publicStringtoString()return"DownloadInfo[url="+url+",pos="pos+",+fileSize+",fileName="+fileName *获取 *@returnprivateint{intfileSize=-1;try{URLurl=newHttpURLConnectionconn=(HttpURLConnection)url.openConnectionintstateCode=conn.getResponseCode();if(stateCode=={fileSize=conn.getContentLength();returnfileSize;}}catch(MalformedURLException{}catch(IOException{}return}}publicclassDownloadThreadextendsThreadprivateDownloadInfoprivateRandomAccessFileprivatebooleanisStop=privatebooleanisFinish=privatestaticintBUFFER_SIZE=8*1024;publicDownloadThread(DownloadInfoinfo){=}publicsynchronizedbooleanisFinish()return publicsynchronizedvoidsetStop(booleanisStop)this.isStop= publicsynchronizedbooleanisStop()return publicvoidrun()while(!isStop()&&!isFinish())tryURLurl=newHttpURLConnectioncon=(HttpURLConnection)Stringprop="bytes="+info.getPos()+"-con.setRequestProperty("RANGE",InputStreamis=raf=newRandomAccessFile(info.getFileName(),byte[]buffer=newintb=-while((b=is.read(buffer))!=-1&&!isStop())raf.write(buffer,0,info.setPos(info.getPos()+intpercent=(int)(100*info.getPos()/System.out.println(info.getFileName()+"已 +percent+ if(!isStop()) isFinish= }catch(MalformedURLExceptione)}catch(IOExceptione)}finallytry}catch(IOExceptione)}}}}}创建eDonlaTha类,在ain方法中,创建两个DwnlaTha类的对象,调用该类的a方法,启动两个线程测试多线程。publicclassTestDownloadThreadpublicstaticvoidmain(String[]args)DownloadInfoinfo1=newDownloadInfoinfo2=newDownloadInfo(DownloadThreadthread1=newDownloadThread(info1);DownloadThreadthread2=newDownloadThread(info2);}}创建Donloaae类,继承Ja类,用来表示断点续传工具的界面。在该类中创建内部类PoPanel,表示的进度条Panl。在Donloaame类中创建内部类DwnlaI使其实现序列化接口,表示一个项的所有信息和操作。在Dwnlaam类中创建aTabPan方法,ini方法,aonnPan方法以及构造方法初始化界面。publicclassDownloadFrameextendsprivateclassProgressPanelextendsJPanelprivateintonline;publicProgressPanel(){}publicvoidpaint(Graphics{for(inti=0;i<online;{g.fill3DRect(6+i*4,8,3,16,} privateclassDownloadItemimplementsSerializableprivatestaticprivatestaticfinalprivatestaticintSTATUS_INIT1;intSTATUS_START2;//开始状态,按钮上显示intSTATUS_STOP=3;//停止状态,按钮上显示ProgressPanelprogressPanel;JLabellabel;JButtonbutton; DownloadInfo transientDownloadThread intstatus;//当 voidsetActionListener()button.addActionListener(newActionListener()publicvoidactionPerformed(ActionEvente)switch(status)caseStringurl="请输 地址if(url==null||url.length()==StringfileName=if(fileName==null||url.length()==Filefile=newtry//创建 //创建 info=newDownloadInfo(url,//创 线thread=new//设 状}catch(IOExceptione1) case case thread=new voidinit()status= 的文件 voidstart()status= voidstop()status= voidupdate()if(thread!=null)if(thread.isFinish()) }elseif(info.getFileSize()!=-1)intpercent=(int)(info.getPos()*100/progressPanel.online=label.setText("文件:"+info.getFileName()+"正 中 +percent+}elselabel.setText("文件:"+info.getFileName()+"正 中}publicDownloadItem()}}}}}在DownloadFrame类中定义THREAD_NUM常量,表示同时的文件数量;定义List类型}}}privatestaticfinalintTHREAD_NUM=privateList<DownloadItem>itemList=new在DownloadFrame类中创建createTabPane方法和createContentPaneprivateJPanelcreateTabPane()JPanelp=newJPanel(newGridLayout(10,1,6,6));p.setBackground(newColor(35,31,p.setBorder(newEmptyBorder(8,8,8,for(inti=0;i<THREAD_NUM;i++){DownloadItemitem=newDownloadItem();//JLabellabel=newitem.label=label;//JButtonbtn=newJButton();btn.setForeground(newColor(249,250,251));btn.setBackground(newColor(220,31,36));item.button=btn;//ProgressPanelpp=newgressPanel=JPanelp1=newJPanel(newBorderLayout(6,p1.setBackground(newColor(35,31,32));p1.add(BorderLayout.EAST,btn);p1.add(BorderLayout.CENTER,pp);}return}privateComponentcreateContentPane()JPanelp=newJPanel(newBorderLayout());p.setBackground(newColor(35,31,32));p.add(BorderLayout.CENTER,createTabPane());returnp;}publicDownloadFrame()setSize(500,400);}守护线程,用来更新项的显示信息。privateclassInnerThreadextendsThreadpublicInnerThread(){}publicvoidrun(){while(true){tryfor(inti=0;i<itemList.size();i++){}}catch(InterruptedExceptione)}}}}在DownloadFrame类中定义innerThread属性,该属性使用transient关键字修饰,序列化DownloadFrame类时,不序列化innerThread属性;定义downloadInfoFile常量,设置序列化privatetransientInnerThreadinnerThread=newprivatestaticfinalStringdownloadInfoFile=privatestaticvoidsave(DownloadFrameframe)Filefile=newFile(downloadInfoFile);System.out.println("save:"+file);try{}catch(IOException{ }ObjectOutputStreamoos=newnewObjectOutputStreamoos=newnewFileOutputStream(file));privateprivatestaticDownloadFrameload()Filefile=newifreturnnull;else{System.out.println("load:"+}tryObjectInputStreamois=newObjectInputStream(newDownloadFrameframe=(DownloadFrame)}cuEonreturn} publicvoidinit()this.addWindowListener(new{publicvoidwindowClosing(WindowEvente)(itemList!=null&&itemList.size()>{for(DownloadItemitem:itemList)if(item.status==DownloadItem.STATUS_START)}}}}(itemList!=null&&itemList.size()>for(DownloadItemitem:itemList){}{}innerThread=newInnerThread();}publicstaticvoidmain(String[]args)DownloadFrameframe=load();if(frame==null){frame=new}}publicclassDownloadInfoimplementsSerializableprivatestaticfinallongserialVersionUID=privateStringprivatelongprivatelongprivateStringfileName;publicDownloadInfo(Stringurl,StringfileName)this.url=this.fileName=this.fileSize= publicStringgetUrl()return publicvoidsetUrl(Stringurl)this.url= publiclonggetPos()return publicvoidsetPos(longpos)this.pos=}publicStringgetFileName()return}publicvoidsetFileName(String{this.fileName=}publiclonggetFileSize()return publicvoidsetFileSize(longfileSize)this.fileSize=}*获取要文件的大*privateintfecthFileSize()intfileSize=-tryURLurl=newHttpURLConnectionconn=intstateCode=if(stateCode=={fileSize=return}}catch(MalformedURLExceptione)}catch(IOExceptione)}return}}publicclassDownloadThreadextendsThreadprivateprivateprivateprivateprivateDownloadInfoRandomAccessFileraf;booleanisStop=false;booleanisFinish=false;staticintBUFFER_SIZE=8*publicDownloadThread(DownloadInfoinfo)= publicsynchronizedbooleanisFinish()return publicsynchronizedvoidsetStop(booleanisStop)this.isStop= publicsynchronizedbooleanisStop()return publicvoidrun()while(!isStop()&&!isFinish())tryURLurl=newURL(info.getUrl()); HttpURLConnectioncon=(HttpURLConnection) Stringprop="bytes="+info.getPos()+"- con.setRequestProperty("RANGE", InputStreamis=con.getInputStream(); raf=newRandomAccessFile(info.getFileName(), byte[]buffer=new intb=- while((b=is.read(buffer))!=-1&&!isStop()) raf.write(buffer,0, info.setPos(info.getPos()+}if(!isStop())isFinish=}}catch{}catch(IOExceptione)}finallytry}catch(IOExceptione)}}}}}publicclassDownloadFrameextendsJFrameprivateprivateprivatestaticfinalintTHREAD_NUM=List<DownloadItem>itemList=newArrayList<DownloadItem>();transientInnerThreadinnerThread=newInnerThread();privatestaticfinalStringdownloadInfoFile=publicDownloadFrame()setSize(500,400);}public{this.addWindowListener(newpublicvoidwindowClosing(WindowEvente)if(itemList!=null&&itemList.size()>0)for(DownloadItemitem:itemList)if(item.status==DownloadItem.STATUS_START) (itemList!=null&&>{for(DownloadItemitem:itemList)}}innerThread=new}privateComponentcreateContentPane()JPanelp=newJPanel(newp.setBackground(newColor(35,31,p.add(BorderLayout.CENTER,return}privateJPanelcreateTabPane()JPanelp=newJPanel(newGridLayout(10,p.setBackground(newColor(35,31,p.setBorder(newEmptyBorder(8,8,8,for(inti=0;i<THREAD_NUM;i++)DownloadItemitem=new//JLabellabel=newitem.labelitem.label=//JButtonbtn=newbtn.setForeground(newColor(249,250,btn.setBackground(newColor(220,31,item.button=btn;//ProgressPanelpp=newgressPanel=pp;JPanelp1=newJPanel(newBorderLayout(6,p1.setBackground(newColor(35,31,p1.add(BorderLayout.EAST,p1.add(BorderLayout.CENTER, return privateclassProgressPanelextendsJPanelprivateintpublicProgressPanel()}publicvoidpaint(Graphicsg)f

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论