最新整理java经典代码

VIP免费
2024-12-11 1 0 286KB 40 页 5.9玖币
侵权投诉
Java 实现 ftp 功能
importsun.net.ftp.*;
importsun.net.*;
importjava.awt.*;
importjava.awt.event.*;
importjava.applet.*;
importjava.io.*;
publicclassFtpAppletextendsApplet
{
FtpClientaftp;
DataOutputStreamoutputs;
TelnetInputStreamins;
TelnetOutputStreamouts;
TextArealsArea;
LabelLblPrompt;
ButtonBtnConn;
ButtonBtnClose;
TextFieldTxtUID;
TextFieldTxtPWD;
TextFieldTxtHost;
intch;
publicStringa="没有连接主机";
Stringhostname="";
publicvoidinit(){
setBackground(Color.white);
setLayout(newGridBagLayout());
GridBagConstraintsGBC=newGridBagConstraints(
);
LblPrompt=newLabel("没有连接主机");
LblPrompt.setAlignment(Label.LEFT);
BtnConn=newButton("连接");
BtnClose=newButton("断开");
BtnClose.enable(false);
TxtUID=newTextField("",15);
TxtPWD=newTextField("",15);
TxtPWD.setEchoCharacter(*);
TxtHost=newTextField("",20);
LabelLblUID=newLabel("UserID:");
LabelLblPWD=newLabel("PWD:");
LabelLblHost=newLabel("Host:");
lsArea=newTextArea(30,80);
lsArea.setEditable(false);
GBC.gridwidth=GridBagConstraints.REMAINDER;
GBC.fill=GridBagConstraints.HORIZONTAL;
((GridBagLayout)getLayout()).setConstraints(LblPro
mpt,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(LblPW
D,GBC);
add(LblPWD);
GBC.gridwidth=1;
((GridBagLayout)getLayout()).setConstraints(TxtPW
D,GBC);
add(TxtPWD);
GBC.gridwidth=1;
GBC.weightx=2;
((GridBagLayout)getLayout()).setConstraints(BtnCon
n,GBC);
add(BtnConn);
GBC.gridwidth=GridBagConstraints.REMAINDER;
((GridBagLayout)getLayout()).setConstraints(BtnClos
e,GBC);
add(BtnClose);
GBC.gridwidth=GridBagConstraints.REMAINDER;
GBC.fill=GridBagConstraints.HORIZONTAL;
((GridBagLayout)getLayout()).setConstraints(lsArea,
GBC);
add(lsArea);
}
publicbooleanconnect(Stringhostname,Stringuid,St
ringpwd)
{
this.hostname=hostname;
LblPrompt.setText("正在连接,请等待.....");
try{
aftp=newFtpClient(hostname);
aftp.login(uid,pwd);
aftp.binary();
showFileContents();
}
catch(FtpLoginExceptione){
a="无权限与主机:"+hostname+"连接!";
LblPrompt.setText(a);
returnfalse;
}
catch(IOExceptione){
a="连接主机:"+hostname+"失败!";
LblPrompt.setText(a);
returnfalse;
}
catch(SecurityExceptione)
{
a="无权限与主机:"+hostname+"连接!";
LblPrompt.setText(a);
returnfalse;
}
LblPrompt.setText("连接主机:"+hostname+"成功!");
returntrue;
}
publicvoidstop()
{
try
{
aftp.closeServer();
}
catch(IOExceptione)
{
}
}
publicvoidpaint(Graphicsg){
}
publicbooleanaction(Eventevt,Objectobj)
{
if(evt.target==BtnConn)
{
LblPrompt.setText("正在连接,请等待.....");
if(connect(TxtHost.getText(),TxtUID.getText(),TxtP
WD.getText()))
{
BtnConn.setEnabled(false);
BtnClose.setEnabled(true);
}
returntrue;
}
if(evt.target==BtnClose)
{
stop();
BtnConn.enable(true);
BtnClose.enable(false);
LblPrompt.setText(" 与主机"+hostname+" 连接已断
!");
returntrue;
}
returnsuper.action(evt,obj);
}
publicbooleansendFile(Stringfilepathname){
booleanresult=true;
if(aftp!=null)
{
LblPrompt.setText("正在粘贴文件,请耐心等待....");
Stringcontentperline;
try{
a="粘贴成功!";
Stringfg=newString("\\");
intindex=filepathname.lastIndexOf(fg);
Stringfilename=filepathname.substring(index+1);
FilelocalFile;
localFile=newFile(filepathname);
RandomAccessFilesendFile=newRandomAccessFil
e(filepathname,"r");
//
sendFile.seek(0);
outs=aftp.put(filename);
outputs=newDataOutputStream(outs);
while(sendFile.getFilePointer()<sendFile.length())
{
ch=sendFile.read();
outputs.write(ch);
}
outs.close();
sendFile.close();
}
catch(IOExceptione){
a="粘贴失败!";
result=false;
}
LblPrompt.setText(a);
showFileContents();
}
else{
result=false;
}
returnresult;
}
publicvoidshowFileContents()
{
StringBufferbuf=newStringBuffer();
lsArea.setText("");
try
{
ins=aftp.list();
while((ch=ins.read())>=0){
buf.append((char)ch);
}
lsArea.appendText(buf.toString());
ins.close();
}
catch(IOExceptione)
{
}
}
publicstaticvoidmain(Stringargs[]){
Framef=newFrame("FTPClient");
f.addWindowListener(newWindowAdapter()
{
publicvoidwindowClosing(WindowEvente
){
System.exit(0);
}
});
FtpAppletftp=newFtpApplet();
ftp.init();
ftp.start();
f.add(ftp);
f.pack();
f.setVisible(true);
}
}
Java URL 编程
importjava.io.*;
importjava.net.*;
//
//
//GetHost.java
//
//
publicclassGetHost
{
publicstaticvoidmain(Stringarg[]){
if(arg.length>=1){
InetAddress[]Inet;
inti=1;
try{
for(i=1;i<=arg.length;i++){
Inet=InetAddress.getAllByName(arg[i-1]);
for(intj=1;j<=Inet.length;j++){
System.out.print(Inet[j-1].toString());
System.out.print("\n");
}
}
}
catch(UnknownHostExceptione){
System.out.print("UnknownHostName!"+arg[i-1]);
}
}
else{
System.out.print("Usagejava/jviewGetIp<hostname
>");
}
}
}
</pre>
</p>
<p>
<pre>
<fontcolor=red>Example2</font>
<ahref="GetHTML.java">downloadnow</a>
//GetHTML.java
/**
*Thisisaprogramwhichcanreadinformationfrom
awebserver.
*@version1.02000/01/01
*@authorjdeveloper
**/
importjava.net.*;
importjava.io.*;
publicclassGetHTML{
publicstaticvoidmain(Stringargs[]){
if(args.length<1){
System.out.println("USAGE:javaGetHTMLhttpaddr
ess");
System.exit(1);
}
StringsURLAddress=newString(args[0]);
URLurl=null;
try{
url=newURL(sURLAddress);
}catch(MalformedURLExceptione){
System.err.println(e.toString());
System.exit(1);
}
try{
InputStreamins=url.openStream();
BufferedReaderbreader=newBufferedReader(new
InputStreamReader(ins));
Stringinfo=breader.readLine();
while(info!=null){
System.out.println(info);
info=breader.readLine();
}
}
catch(IOExceptione){
System.err.println(e.toString());
System.exit(1);
}
}
}
Java RMI 编程
<b>Step1:ImplementstheinterfaceofRemoteServ
erasSimpleCounterServer.java</b>
publicinterfaceSimpleCounterServerextendsjava.
rmi.Remote
{
publicintgetCount()throwsjava.rmi.RemoteExcep
tion;

}
CompileitwithjavacSimpleCounterServer.java
<b>Step2:ProducetheimplementfileSimpleCou
nterServerImpl.javaas</b>
importjava.rmi.*;
importjava.rmi.server.UnicastRemoteObject;
//
//
//SimpleCounterServerImpl
//
//
publicclassSimpleCounterServerImpl
extendsUnicastRemoteObject
implementsSimpleCounterServer
{
privateintiCount;
publicSimpleCounterServerImpl()throwsjava.rmi.
RemoteException
{
iCount=0;
}
publicintgetCount()throwsRemoteException
{
return++iCount;
}
publicstaticvoidmain(Stringargs[])
{
System.setSecurityManager(newRMISecurityM
anager());
try
{
SimpleCounterServerImplserver=newSimpl
eCounterServerImpl();
System.out.println("SimpleCounterServercrea
ted");
Naming.rebind("SimpleCounterServer",server)
;
System.out.println("SimpleCounterServerregi
stered");
}
catch(RemoteExceptionx)
{
x.printStackTrace();
}
catch(Exceptionx)
{
x.printStackTrace();
}
}
}
ComplileitwithjavacSimpleCounterServerImpl.java
<b>Step3:ProduceskeletonandstubfilewithrmicS
impleCounterServerImpl</b>
Youwillgettwoclassfiles:
1.SimpleCounterServerImpl_Stub.class
2.SimpleCounterServerImpl_Skel.class
<b>Step4:startrmiregistry</b>
<b>Step5:javaSimpleCounterServerImpl</b>
<b>Step6:ImplementstheClientApplettoinvoketh
eRemotemethod</b>
File:SimpleCounterApplet.javaas
importjava.applet.Applet;
importjava.rmi.*;
importjava.awt.*;
//
//
//SimpleCounterApplet
//
//
publicclassSimpleCounterAppletextendsApplet
{
Stringmessage="";
Stringmessage1="";
publicvoidinit()
{
setBackground(Color.white);
try
{
SimpleCounterServersever=(SimpleCounter
Server)
Naming.lookup("//"+getCodeBase().getHost
()+"/SimpleCounterServer");
message1="//"+getCodeBase().getHost()+"/S
impleCounterServer";
message=String.valueOf(sever.getCount());
}
catch(Exceptionx)
{
x.printStackTrace();
message=x.toString();
}
}
publicvoidpaint(Graphicsg)
{
g.drawString("Numberis"+message,10,10);
g.drawString("Numberis"+message1,10,30);
}
}
<b>step7createanHtmlFilermi.htm:</b>
<html>
<body>
<appletcode="SimpleCounterApplet.class"width="5
00"height="150">
</applet>
</body>
</html>
Java CORBA 入门
BelowisasimpleexampleofaCORBAprogram
downloadthesourcefile
<b>1.produceaidlfilelikethis</b>
hello.idl
moduleHelloApp{
interfaceHello{
stringsayHello();
};
};
<b>2.producestubandskeletonfilesthroughidltojav
a.exe</b>
idltojavahello.idl
idltojavaisnownamedasidlj.exeandisincludedin
theJDK.
<b>3.writeaserverprogramlikethis</b>
//HelloServer.java
银杏树www.516fc.net
苏州美肤www.szpfmr.net
苏州祛斑www.szquban.net
苏州除皱www.szchuzhou.com
苏州脱毛www.sztuomao.com.cn
苏州人才网www.xinyie.com
南京调查公司www.jslycs.com
南京调查公司www.penqiang.net

importHelloApp.*;
importorg.omg.CosNaming.*;
importorg.omg.CosNaming.NamingContextPackage.
*;
importorg.omg.CORBA.*;
importjava.io.*;
classHelloServantextends_HelloImplBase
{
publicStringsayHello()
{
return"\nHelloworld!!\n";
}

}
publicclassHelloServer{
publicstaticvoidmain(Stringargs[])
{
try{
//createandinitializetheORB
ORBorb=ORB.init(args,null);
//createservantandregisteritwiththeORB
HelloServanthelloRef=newHelloServant();
orb.connect(helloRef);
//gettherootnamingcontext
org.omg.CORBA.ObjectobjRef=
orb.resolve_initial_references("NameService");
NamingContextncRef=NamingContextHelper.nar
row(objRef);
//bindtheObjectReferenceinNaming
NameComponentnc=newNameComponent("Hell
o","");
NameComponentpath[]={nc};
ncRef.rebind(path,helloRef);
//waitforinvocationsfromclients
java.lang.Objectsync=newjava.lang.Object()
;
synchronized(sync){
sync.wait();
}
}catch(Exceptione){
System.err.println("ERROR:"+e);
e.printStackTrace(System.out);
}
}
}
<b>4.writeaclientprogramlikethis</b>
//HelloClient.java
importHelloApp.*;
importorg.omg.CosNaming.*;
importorg.omg.CORBA.*;
publicclassHelloClient
{
publicstaticvoidmain(Stringargs[])
{
try{
//createandinitializetheORB
ORBorb=ORB.init(args,null);
//gettherootnamingcontext
org.omg.CORBA.ObjectobjRef=
orb.resolve_initial_references("NameService");
NamingContextncRef=NamingContextHelpe
r.narrow(objRef);
//test
System.out.println("OK..");
//resolvetheObjectReferenceinNaming
NameComponentnc=newNameComponent(
"Hello","");
NameComponentpath[]={nc};
HellohelloRef=HelloHelper.narrow(ncRef.re
solve(path));
//calltheHelloserverobjectandprintresults
//Stringoldhello=helloRef.lastMessage();
//System.out.println(oldhello);
StringHello=helloRef.sayHello();
System.out.println(Hello);
}catch(Exceptione){
System.out.println("ERROR:"+e);
e.printStackTrace(System.out);
}
}
}
<b>5.compliethesefiles</b>
javac*.javaHelloApp/*.java
<b>6.runtheapplication</b>

a.firstyouvetoruntheNameServicepriortothe
otherslikethis
c:\>tnameserv
b.runserver
c:\>javaHelloServer
c.runclient
c:\>javaHelloClient
利用 RamdonAccessFile 来实现文件的追加
RamdonAccessFile
大,可以利用它的
length()seek()方法来轻松实现文件的追加,相信
我下面这个例子是
很容写入length()出长
(以 byte 为单位),
在用 seek()移动到文件末尾,继续添加,最后显示
记录。
importjava.io.*;
publicclassIOStreamDemo{
 publicstaticvoidmain(String[]args){
  try{
   RandomAccessFilerf1=newRandomAccess
File("d:\\jeru.txt","rw");
   for(inti=0;i&lt;10;i++) {
    rf1.writeBytes("xixi,thisisline"+i+"\n");
   }
   rf1.close();
 
   inti=0;
   Stringrecord=newString();
   RandomAccessFilerf2=newRandomAccess
File("d:\\jeru.txt","rw");
   rf2.seek(rf2.length());
   rf2.writeBytes("lala,appendline"+"\n");
   rf2.close();
  
   RandomAccessFilerf3=newRandomAccess
File("d:\\jeru.txt","r");
   while((record=rf3.readLine())!=null){
    i++;
    System.out.println("Value"+i+":"+record);
   }
   rf3.close();
 {}catch(Exceptione){}
}
}
JavaMail 包装成简单的 Sendmail
packagesteeven;
/*
Calss:Sendmail
Author:steeven@kali.com.cn
QQ:7461522
Date:11/13/2001
Notes:
Findsamplesinmain();
Ifyousendmailonlyfrom/tointranet,changedo
mainasuneed.
Setup:
1.changehost,mailFooter
*/
importjava.util.*;
importjava.sql.*;
importjavax.mail.*;
importjavax.mail.internet.*;
importjavax.activation.*;
publicclassSendmailextendsCommon{
publicStringhost="smtpServer";//smtpser
ver
staticStringmailFooter="\n\n\n 此邮件由 WebMail
发送{http://www/mail.jsp\n\n";
Stringdomain="company";
booleansessionDebug;
Messagemsg;
Multipartmultipart;
publicSendmail()throwsException{
Propertiesprops=System.getProperties();
props.put("mail.host",host);
props.put("mail.transport.protocol","smtp");
Sessionsession=Session.getDefaultInstance(props
,null);
//SetdebugontheSessionsowecanseewhatisgo
ingon
//Passingfalsewillnotechodebuginfo,andpassin
gtrue
//will.
session.setDebug(sessionDebug);
//InstantiateanewMimeMessageandfillitwithth
e
//requiredinformation.
msg=newMimeMessage(session);
msg.setSentDate(newjava.util.Date());
multipart=newMimeMultipart();
msg.setContent(multipart);
}
publicSendmail(Stringto,Stringfrom,Stringsubjec
t,Stringbody)throwsException{
this();
this.setSendTo(to);
this.setFrom(from);
this.setSubject(subject);
this.setBody(body);
}
publicSendmail(String[]to,Stringfrom,Stringsubj
ect,Stringbody)throwsException{
this();
this.setSendTo(to);
this.setFrom(from);
this.setSubject(subject);
this.setBody(body);
}
publicvoidsetHost(Stringhost)throwsException{
this.host=host;
}
voidsetFrom(Stringfrom)throwsException{
摘要:

Java实现ftp功能import sun.net.ftp.*; import sun.net.*; import java.awt.*; import java.awt.event.*; import java.applet.*; import java.io.*; public class FtpApplet extends Applet { FtpClient aftp; DataOutputStream outputs ; TelnetInputStream ins; TelnetOutputStream outs; TextArea lsArea; Label    LblPromp...

展开>> 收起<<
最新整理java经典代码.doc

共40页,预览8页

还剩页未读, 继续阅读

声明:本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。玖贝云文库仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知玖贝云文库,我们立即给予删除!
分类:计算机 价格:5.9玖币 属性:40 页 大小:286KB 格式:DOC 时间:2024-12-11

开通VIP享超值会员特权

  • 多端同步记录
  • 高速下载文档
  • 免费文档工具
  • 分享文档赚钱
  • 每日登录抽奖
  • 优质衍生服务
/ 40
客服
关注