java经典代码(最全面).doc_第1页
java经典代码(最全面).doc_第2页
java经典代码(最全面).doc_第3页
java经典代码(最全面).doc_第4页
java经典代码(最全面).doc_第5页
已阅读5页,还剩35页未读 继续免费阅读

下载本文档

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

文档简介

Java实现ftp功能.ftp.*; .*; importjava.awt.*; importjava.awt.event.*; importjava.applet.*; importjava.io.*; publicclassFtpAppletextendsApplet FtpClientaftp; DataOutputStreamoutputs; TelnetInputStreamins; TelnetOutputStreamouts; TextArealsArea; LabelLblPrompt; ButtonBtnConn; ButtonBtnClose; TextFieldTxtUID; TextFieldTxtPWD; TextFieldTxtHost; intch; publicStringa=没有连接主机; Stringhostname=; publicvoidinit() setBackground(Color.white); setLayout(newGridBagLayout(); GridBagConstraintsGBC=newGridBagConstraints(); LblPrompt=newLabel(没有连接主机); LblPrompt.setAlignment(Label.LEFT); BtnConn=newButton(连接); BtnClose=newButton(断开); BtnClose.enable(false); TxtUID=newTextField(,15); TxtPWD=newTextField(,15); TxtPWD.setEchoCharacter(*); TxtHost=newTextField(,20); LabelLblUID=newLabel(UserID:); LabelLblPWD=newLabel(PWD:); LabelLblHost=newLabel(Host:); lsArea=newTextArea(30,80); lsArea.setEditable(false); GBC.gridwidth=GridBagConstraints.REMAINDER; GBC.fill=GridBagConstraints.HORIZONTAL; (GridBagLayout)getLayout().setConstraints(LblPrompt,GBC); add(LblPrompt); GBC.gridwidth=1; (GridBagLayout)getLayout().setConstraints(LblHost,GBC); add(LblHost); GBC.gridwidth=GridBagConstraints.REMAINDER; (GridBagLayout)getLayout().setConstraints(TxtHost,GBC); add(TxtHost); GBC.gridwidth=1; (GridBagLayout)getLayout().setConstraints(LblUID,GBC); add(LblUID); GBC.gridwidth=1; (GridBagLayout)getLayout().setConstraints(TxtUID,GBC); add(TxtUID); GBC.gridwidth=1; (GridBagLayout)getLayout().setConstraints(LblPWD,GBC); add(LblPWD); GBC.gridwidth=1; (GridBagLayout)getLayout().setConstraints(TxtPWD,GBC); add(TxtPWD); GBC.gridwidth=1; GBC.weightx=2; (GridBagLayout)getLayout().setConstraints(BtnConn,GBC); add(BtnConn); GBC.gridwidth=GridBagConstraints.REMAINDER; (GridBagLayout)getLayout().setConstraints(BtnClose,GBC); add(BtnClose); GBC.gridwidth=GridBagConstraints.REMAINDER; GBC.fill=GridBagConstraints.HORIZONTAL; (GridBagLayout)getLayout().setConstraints(lsArea,GBC); add(lsArea); publicbooleanconnect(Stringhostname,Stringuid,Stringpwd) this.hostname=hostname; LblPrompt.setText(正在连接,请等待.); try aftp=newFtpClient(hostname); aftp.login(uid,pwd); aftp.binary(); showFileContents(); catch(FtpLoginExceptione) a=无权限与主机:+hostname+连接!; LblPrompt.setText(a); returnfalse; catch(IOExceptione) a=连接主机:+hostname+失败!; LblPrompt.setText(a); returnfalse; catch(SecurityExceptione) a=无权限与主机:+hostname+连接!; LblPrompt.setText(a); returnfalse; LblPrompt.setText(连接主机:+hostname+成功!); returntrue; publicvoidstop() try aftp.closeServer(); catch(IOExceptione) publicvoidpaint(Graphicsg) publicbooleanaction(Eventevt,Objectobj) if(evt.target=BtnConn) LblPrompt.setText(正在连接,请等待.); if(connect(TxtHost.getText(),TxtUID.getText(),TxtPWD.getText() BtnConn.setEnabled(false); BtnClose.setEnabled(true); returntrue; if(evt.target=BtnClose) stop(); BtnConn.enable(true); BtnClose.enable(false); LblPrompt.setText(与主机+hostname+连接已断开!); returntrue; returnsuper.action(evt,obj); publicbooleansendFile(Stringfilepathname) booleanresult=true; if(aftp!=null) LblPrompt.setText(正在粘贴文件,请耐心等待.); Stringcontentperline; try a=粘贴成功!; Stringfg=newString(); intindex=filepathname.lastIndexOf(fg); Stringfilename=filepathname.substring(index+1); FilelocalFile; localFile=newFile(filepathname); RandomAccessFilesendFile=newRandomAccessFile(filepathname,r); / sendFile.seek(0); outs=aftp.put(filename); outputs=newDataOutputStream(outs); while(sendFile.getFilePointer()=0) buf.append(char)ch); lsArea.appendText(buf.toString(); ins.close(); catch(IOExceptione) publicstaticvoidmain(Stringargs) Framef=newFrame(FTPClient); f.addWindowListener(newWindowAdapter() publicvoidwindowClosing(WindowEvente) System.exit(0); ); FtpAppletftp=newFtpApplet(); ftp.init(); ftp.start(); f.add(ftp); f.pack(); f.setVisible(true); Java URL编程importjava.io.*; .*; / / /GetHost.java / / publicclassGetHost publicstaticvoidmain(Stringarg) if(arg.length=1) InetAddressInet; inti=1; try for(i=1;i=arg.length;i+) Inet=InetAddress.getAllByName(argi-1); for(intj=1;j=Inet.length;j+) System.out.print(Inetj-1.toString(); System.out.print(n); catch(UnknownHostExceptione) System.out.print(UnknownHostName!+argi-1); else System.out.print(Usagejava/jviewGetIp); Example2 downloadnow /GetHTML.java /* *Thisisaprogramwhichcanreadinformationfromawebserver. *version1.02000/01/01 *authorjdeveloper */ .*; importjava.io.*; publicclassGetHTML publicstaticvoidmain(Stringargs) if(args.length1) System.out.println(USAGE:javaGetHTMLhttpaddress); System.exit(1); StringsURLAddress=newString(args0); URLurl=null; try url=newURL(sURLAddress); catch(MalformedURLExceptione) System.err.println(e.toString(); System.exit(1); try InputStreamins=url.openStream(); BufferedReaderbreader=newBufferedReader(newInputStreamReader(ins); Stringinfo=breader.readLine(); while(info!=null) System.out.println(info); info=breader.readLine(); catch(IOExceptione) System.err.println(e.toString(); System.exit(1); Java RMI编程Step1:ImplementstheinterfaceofRemoteServerasSimpleCounterServer.java publicinterfaceSimpleCounterServerextendsjava.rmi.Remote publicintgetCount()throwsjava.rmi.RemoteException; CompileitwithjavacSimpleCounterServer.java Step2:ProducetheimplementfileSimpleCounterServerImpl.javaas importjava.rmi.*; importjava.rmi.server.UnicastRemoteObject; / / /SimpleCounterServerImpl / / publicclassSimpleCounterServerImpl extendsUnicastRemoteObject implementsSimpleCounterServer privateintiCount; publicSimpleCounterServerImpl()throwsjava.rmi.RemoteException iCount=0; publicintgetCount()throwsRemoteException return+iCount; publicstaticvoidmain(Stringargs) System.setSecurityManager(newRMISecurityManager(); try SimpleCounterServerImplserver=newSimpleCounterServerImpl(); System.out.println(SimpleCounterServercreated); Naming.rebind(SimpleCounterServer,server); System.out.println(SimpleCounterServerregistered); catch(RemoteExceptionx) x.printStackTrace(); catch(Exceptionx) x.printStackTrace(); ComplileitwithjavacSimpleCounterServerImpl.java Step3:ProduceskeletonandstubfilewithrmicSimpleCounterServerImpl Youwillgettwoclassfiles: 1.SimpleCounterServerImpl_Stub.class 2.SimpleCounterServerImpl_Skel.class Step4:startrmiregistry Step5:javaSimpleCounterServerImpl Step6:ImplementstheClientApplettoinvoketheRemotemethod File:SimpleCounterApplet.javaas importjava.applet.Applet; importjava.rmi.*; importjava.awt.*; / / /SimpleCounterApplet / / publicclassSimpleCounterAppletextendsApplet Stringmessage=; Stringmessage1=; publicvoidinit() setBackground(Color.white); try SimpleCounterServersever=(SimpleCounterServer) Naming.lookup(/+getCodeBase().getHost()+/SimpleCounterServer); message1=/+getCodeBase().getHost()+/SimpleCounterServer; message=String.valueOf(sever.getCount(); catch(Exceptionx) x.printStackTrace(); message=x.toString(); publicvoidpaint(Graphicsg) g.drawString(Numberis+message,10,10); g.drawString(Numberis+message1,10,30); step7createanHtmlFilermi.htm: Java CORBA入门BelowisasimpleexampleofaCORBAprogram downloadthesourcefile 1.produceaidlfilelikethis hello.idl moduleHelloApp interfaceHello stringsayHello(); ; ; 2.producestubandskeletonfilesthroughidltojava.exe idltojavahello.idl idltojavaisnownamedasidlj.exeandisincludedintheJDK. 3.writeaserverprogramlikethis /HelloServer.java importHelloApp.*; importorg.omg.CosNaming.*; importorg.omg.CosNaming.NamingContextPackage.*; importorg.omg.CORBA.*; importjava.io.*; classHelloServantextends_HelloImplBase publicStringsayHello() returnnHelloworld!n; publicclassHelloServer publicstaticvoidmain(Stringargs) try /createandinitializetheORB ORBorb=ORB.init(args,null); /createservantandregisteritwiththeORB HelloServanthelloRef=newHelloServant(); orb.connect(helloRef); /gettherootnamingcontext org.omg.CORBA.ObjectobjRef= orb.resolve_initial_references(NameService); NamingContextncRef=NamingContextHelper.narrow(objRef); /bindtheObjectReferenceinNaming NameComponentnc=newNameComponent(Hello,); NameComponentpath=nc; ncRef.rebind(path,helloRef); /waitforinvocationsfromclients java.lang.Objectsync=newjava.lang.Object(); synchronized(sync) sync.wait(); catch(Exceptione) System.err.println(ERROR:+e); e.printStackTrace(System.out); 4.writeaclientprogramlikethis /HelloClient.java importHelloApp.*; importorg.omg.CosNaming.*; importorg.omg.CORBA.*; publicclassHelloClient publicstaticvoidmain(Stringargs) try /createandinitializetheORB ORBorb=ORB.init(args,null); /gettherootnamingcontext org.omg.CORBA.ObjectobjRef= orb.resolve_initial_references(NameService); NamingContextncRef=NamingContextHelper.narrow(objRef); /test System.out.println(OK.); /resolvetheObjectReferenceinNaming NameComponentnc=newNameComponent(Hello,); NameComponentpath=nc; HellohelloRef=HelloHelper.narrow(ncRef.resolve(path); /calltheHelloserverobjectandprintresults /Stringoldhello=helloRef.lastMessage(); /System.out.println(oldhello); StringHello=helloRef.sayHello(); System.out.println(Hello); catch(Exceptione) System.out.println(ERROR:+e); e.printStackTrace(System.out); 5.compliethesefiles javac*.javaHelloApp/*.java 6.runtheapplication a.firstyouvetoruntheNameServicepriortotheotherslikethis c:tnameserv b.runserver c:javaHelloServer c.runclient c:javaHelloClient利用RamdonAccessFile来实现文件的追加RamdonAccessFile是个很好用的类,功能十分强大,可以利用它的 length()和seek()方法来轻松实现文件的追加,相信我下面这个例子是 很容易看懂的,先写入十行,用length()读出长度(以byte为单位), 在用seek()移动到文件末尾,继续添加,最后显示记录。 importjava.io.*; publicclassIOStreamDemo publicstaticvoidmain(Stringargs) try RandomAccessFilerf1=newRandomAccessFile(d:jeru.txt,rw); for(inti=0;i<10;i+) rf1.writeBytes(xixi,thisisline+i+n); rf1.close(); inti=0; Stringrecord=newString(); RandomAccessFilerf2=newRandomAccessFile(d:jeru.txt,rw); rf2.seek(rf2.length(); rf2.writeBytes(lala,appendline+n); rf2.close(); RandomAccessFilerf3=newRandomAccessFile(d:jeru.txt,r); while(record=rf3.readLine()!=null) i+; System.out.println(Value+i+:+record); rf3.close(); catch(Exceptione) 把JavaMail包装成简单的Sendmailpackagesteeven; /* Calss:Sendmail Author: QQ:7461522 Date:11/13/2001 Notes: Findsamplesinmain(); Ifyousendmailonlyfrom/tointranet,changedomainasuneed. Setup: 1.changehost,mailFooter */ importjava.util.*; importjava.sql.*; importjavax.mail.*; ernet.*; importjavax.activation.*; publicclassSendmailextendsCommon publicStringhost=smtpServer;/smtpserver staticStringmailFooter=nnn此邮件由WebMail发送http:/www/mail.jspnn; Stringdomain=company; booleansessionDebug; Messagemsg; Multipartmultipart; publicSendmail()throwsException Propertiesprops=System.getProperties(); props.put(mail.host,host); props.put(tocol,smtp); Sessionsession=Session.getDefaultInstance(props,null); /SetdebugontheSessionsowecanseewhatisgoingon /Passingfalsewillnotechodebuginfo,andpassingtrue /will. session.setDebug(sessionDebug); /InstantiateanewMimeMessageandfillitwiththe /requiredinformation. msg=newMimeMessage(session); msg.setSentDate(newjava.util.Date(); multipart=newMimeMultipart(); msg.setContent(multipart); publicSendmail(Stringto,Stringfrom,Stringsubject,Stringbody)throwsException this(); this.setSendTo(to); this.setFrom(from); this.setSubject(subject); this.setBody(body); publicSendmail(Stringto,Stringfrom,Stringsubject,Stringbody)throwsException this(); this.setSendTo(to); this.setFrom(from); this.setSubject(subject); this.setBody(body); publicvoidsetHost(Stringhost)throwsException this.host=host; voidsetFrom(Stringfrom)throwsException msg.setFrom(newInternetAddress(from+domain); voidsetSendTo(Stringto)throwsException for(inti=0;i<to.length;i+) setSendTo(toi); voidsetSendTo(Stringto)throwsException /System.out.println(sendingmailto:+toi); InternetAddressaddress=newInternetAddress(to+domain); msg.setRecipients(Message.RecipientType.TO,address); voidsetCopyTo(Stringto)throwsException for(inti=0;to!=null&i<to.length;i+) setCopyTo(toi); voidsetCopyTo(Stringto)throwsException /System.out.println(Copyingmailto:+toi); InternetAddressaddress=newInternetAddress(to+domain); msg.setRecipients(Message.RecipientType.CC,address); voidsetSubject(Stringsubject)throwsException sun.misc.BASE64Encoderenc=newsun.misc.BASE64Encoder(); msg.setSubject(=?GB2312?B?+enc.encode(subject.getBytes()+?=); voidsetBody(Stringbody)throwsException MimeBodyPartmessageBodyPart=newMimeBodyPart(); messageBodyPart.setText(body+mailFooter); multipart.addBodyPart(messageBodyPart); voidsetAttachFile(StringfileName)throwsException setAttachFile(fileName,fileName); voidsetAttachFile(StringfileName,Stringname)throwsException MimeBodyPartmessageBodyPart=newMimeBodyPart(); DataSourcesource=newFileDataSource(fileName); messageBodyPart.setDataHandler(newDataHandler(source); messageBodyPart.setFileName(name); multipart.addBodyPart(messageBodyPart); voidsetAttachFile(StringfileName)throwsException for(inti=0;i<fileName.length;i+) setAttachFile(fileNamei0,fileNamei1); publicvoidsend()throwsException Transport.send(msg); publicstaticvoidmain(Stringargs)throwsExcept

温馨提示

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

评论

0/150

提交评论