http://www.blogjava.net/JaVaa/
1.使用URL:
URL url
=
new
URL(
"
ftp://javaa:javaa@172.168.2.222:21/test/javaa.txt
"
);
PrintWriter pw
=
new
PrintWriter(url.openConnection().getOutputStream());
pw.write(
"
this is a test
"
);
pw.flush();
pw.close();
上
面是代碼的片斷,其中URL建構函式的參數可以用不同的訪問協議(比如http,ftp等),"//"後跟著的是使用者名稱和密碼,兩者用":"隔開,緊跟著
是分隔字元"@","@"以後的是IP地址和連接埠,然後是目錄,最後才是我們要寫入的檔案名稱,其中目錄是必須存在的,否則會拋出
FileNotFoundException,檔案可以是不存在的,不存在的時候就會建立檔案,否則就會用新的內容覆蓋以前的內容;
2.使用FtpClient:
FtpClient ftpClient
=
new
FtpClient();
ftpClient.openServer(
"
172.168.2.222
"
,
21
);
//
IP地址和連接埠
ftpClient.login(
"
javaa
"
,
"
javaa
"
);
//
使用者名稱和密碼,匿名登陸的話使用者名稱為anonymous,密碼為非Null 字元串
ftpClient.cd(
"
test
"
);
//
切換到test目錄
PrintWriter pw
=
new
PrintWriter(ftpClient.put(
"
javaa.txt
"
));
//
寫入的檔案名稱
pw.write(
"
this is a test
"
);
pw.flush();
pw.close();
3.用PASV模式傳送資料的FtpClient
import sun.net.ftp.FtpClient;
import java.net.Socket;
import java.io.IOException;
public class PasvFtpClient
extends FtpClient{
/**
* FTP伺服器的地址
*/
private String serverAddr;
/**
* 串連到FTP伺服器的Socket
*/
private Socket socket;
/**
* 仿造父類定義的靜態變數
*/
protected final static int FTP_ERROR=3;
/**
* 仿造父類定義的靜態變數
*/
protected final static int FTP_SUCCESS=1;
public PasvFtpClient(String s) throws IOException{
super(s);
serverAddr=s;
socket=null;
}
public PasvFtpClient(String s,int i) throws IOException{
super(s,i);
serverAddr=s;
socket=null;
}
public PasvFtpClient(){
super();
socket=null;
}
/**
* 複寫的主要部分,父類採用PORT模式,這裡改為PASV模式
* @param s 傳入的FTP命令
* @return 串連到FTP伺服器的Socket
* @throws IOException
*/
protected Socket openDataConnection(String s) throws IOException{
if (socket==null){
String s1="PASV";
if (issueCommand(s1)==FTP_ERROR){
MyFtpProtocolException ftpprotocolexception=new MyFtpProtocolException(
"PASV");
throw ftpprotocolexception;
}
String responseStr=this.getResponseString();
int location=responseStr.lastIndexOf(",");
int n=Integer.parseInt(responseStr.substring(location+1,
responseStr.indexOf(")")));
responseStr=responseStr.substring(0,location);
location=responseStr.lastIndexOf(",");
int m=Integer.parseInt(responseStr.substring(location+1,
responseStr.length()));
socket=new Socket(serverAddr,m*256+n);
}
if (issueCommand(s)==FTP_ERROR){
MyFtpProtocolException ftpprotocolexception1=new MyFtpProtocolException(s);
throw ftpprotocolexception1;
}
return socket;
}
/**
* 關閉與FTP伺服器的串連
* @throws IOException
*/
public void closeServer() throws IOException{
socket.close();
socket=null;
super.closeServer();
}
/**
* 開啟與FTP伺服器的串連
* @param s FTP伺服器位址
* @param i FTP伺服器連接埠
* @throws IOException
*/
public void openServer(String s,int i) throws IOException{
super.openServer(s,i);
serverAddr=s;
}
}
/**
* 自訂的FTP異常類
*/
class MyFtpProtocolException
extends IOException{
MyFtpProtocolException(String s){
super(s);
}
}