|
1.使用URL:
URLurl=newURL("ftp://javaa:javaa@172.168.2.222:21/test/javaa.txt");
PrintWriterpw=newPrintWriter(url.openConnection().getOutputStream());
pw.write("thisisatest");
pw.flush();
pw.close();
上面是代码的片断,其中URL构造函数的参数可以用不同的访问协议(比如http,ftp等),"//"后跟着的是用户名和密码,两者用":"隔 开,紧跟着是分隔符"@","@"以后的是IP地址和端口,然后是目录,最后才是我们要写入的文件名,其中目录是必须存在的,否则会抛出 FileNotFoundException,文件可以是不存在的,不存在的时候就会新建文件,否则就会用新的内容覆盖以前的内容;
2.使用FtpClient:
FtpClientftpClient=newFtpClient();
ftpClient.openServer("172.168.2.222",21);//IP地址和端口
ftpClient.login("javaa","javaa");//用户名和密码,匿名登陆的话用户名为anonymous,密码为非空字符串
ftpClient.cd("test");//切换到test目录
PrintWriterpw=newPrintWriter(ftpClient.put("javaa.txt"));//写入的文件名
pw.write("thisisatest");
pw.flush();
pw.close();
3.用PASV模式传送数据的FtpClientimportsun.net.ftp.FtpClient;
importjava.net.Socket;
importjava.io.IOException;
publicclassPasvFtpClient
extendsFtpClient{
/**
*FTP服务器的地址
*/
privateStringserverAddr;
/**
*连接到FTP服务器的Socket
*/
privateSocketsocket;
/**
*仿造父类定义的静态变量
*/
protectedfinalstaticintFTP_ERROR=3;
/**
*仿造父类定义的静态变量
*/
protectedfinalstaticintFTP_SUCCESS=1;
publicPasvFtpClient(Strings)throwsIOException{
super(s);
serverAddr=s;
socket=null;
}
publicPasvFtpClient(Strings,inti)throwsIOException{
super(s,i);
serverAddr=s;
socket=null;
}
publicPasvFtpClient(){
super();
socket=null;
}
/**
*复写的主要部分,父类采用PORT模式,这里改为PASV模式
*@params传入的FTP命令
*@return连接到FTP服务器的Socket
*@throwsIOException
*/
protectedSocketopenDataConnection(Strings)throwsIOException{
if(socket==null){
Strings1="PASV";
if(issueCommand(s1)==FTP_ERROR){
MyFtpProtocolExceptionftpprotocolexception=newMyFtpProtocolException(
"PASV");
throwftpprotocolexception;
}
StringresponseStr=this.getResponseString();
intlocation=responseStr.lastIndexOf(",");
intn=Integer.parseInt(responseStr.substring(location+1,
responseStr.indexOf(")")));
responseStr=responseStr.substring(0,location);
location=responseStr.lastIndexOf(",");
intm=Integer.parseInt(responseStr.substring(location+1,
responseStr.length()));
socket=newSocket(serverAddr,m*256+n);
}
if(issueCommand(s)==FTP_ERROR){
MyFtpProtocolExceptionftpprotocolexception1=newMyFtpProtocolException(s);
throwftpprotocolexception1;
}
returnsocket;
}
/**
*关闭与FTP服务器的连接
*@throwsIOException
*/
publicvoidcloseServer()throwsIOException{
socket.close();
socket=null;
super.closeServer();
}
/**
*打开与FTP服务器的连接
*@paramsFTP服务器地址
*@paramiFTP服务器端口
*@throwsIOException
*/
publicvoidopenServer(Strings,inti)throwsIOException{
super.openServer(s,i);
serverAddr=s;
}
}
/**
*自定义的FTP异常类
*/
classMyFtpProtocolException
extendsIOException{
MyFtpProtocolException(Strings){
super(s);
}
} |
|
|