⑴ FTP客戶端程序設計(java)
package jing.upfile;
import sun.net.ftp.*;
import sun.net.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.StringTokenizer;
/**
FTP遠程命令列表<br>
USER PORT RETR ALLO DELE SITE XMKD CDUP FEAT<br>
PASS PASV STOR REST CWD STAT RMD XCUP OPTS<br>
ACCT TYPE APPE RNFR XCWD HELP XRMD STOU AUTH<br>
REIN STRU SMNT RNTO LIST NOOP PWD SIZE PBSZ<br>
QUIT MODE SYST ABOR NLST MKD XPWD MDTM PROT<br>
在伺服器上執行命令,如果用sendServer來執行遠程命令(不能執行本地FTP命令)的話,所有FTP命令都要加上\r\n<br>
ftpclient.sendServer("XMKD /test/bb\r\n"); //執行伺服器上的FTP命令<br>
ftpclient.readServerResponse一定要在sendServer後調用<br>
nameList("/test")獲取指目錄下的文件列表<br>
XMKD建立目錄,當目錄存在的情況下再次創建目錄時報錯<br>
XRMD刪除目錄<br>
DELE刪除文件<br>
* <p>Title: 使用JAVA操作FTP伺服器(FTP客戶端)</p>
* <p>Description: 上傳文件的類型及文件大小都放到調用此類的方法中去檢測,比如放到前台JAVASCRIPT中去檢測等
* 針對FTP中的所有調用使用到文件名的地方請使用完整的路徑名(絕對路徑開始)。
* </p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: 靜靖工作室</p>
* @author 歐朝敬 13873195792
* @version 1.0
*/
public class FtpUpfile {
private FtpClient ftpclient;
private String ipAddress;
private int ipPort;
private String userName;
private String PassWord;
/**
* 構造函數
* @param ip String 機器IP
* @param port String 機器FTP埠號
* @param username String FTP用戶名
* @param password String FTP密碼
* @throws Exception
*/
public FtpUpfile(String ip, int port, String username, String password) throws
Exception {
ipAddress = new String(ip);
ipPort = port;
ftpclient = new FtpClient(ipAddress, ipPort);
//ftpclient = new FtpClient(ipAddress);
userName = new String(username);
PassWord = new String(password);
}
/**
* 構造函數
* @param ip String 機器IP,默認埠為21
* @param username String FTP用戶名
* @param password String FTP密碼
* @throws Exception
*/
public FtpUpfile(String ip, String username, String password) throws
Exception {
ipAddress = new String(ip);
ipPort = 21;
ftpclient = new FtpClient(ipAddress, ipPort);
//ftpclient = new FtpClient(ipAddress);
userName = new String(username);
PassWord = new String(password);
}
/**
* 登錄FTP伺服器
* @throws Exception
*/
public void login() throws Exception {
ftpclient.login(userName, PassWord);
}
/**
* 退出FTP伺服器
* @throws Exception
*/
public void logout() throws Exception {
//用ftpclient.closeServer()斷開FTP出錯時用下更語句退出
ftpclient.sendServer("QUIT\r\n");
int reply = ftpclient.readServerResponse(); //取得伺服器的返回信息
}
/**
* 在FTP伺服器上建立指定的目錄,當目錄已經存在的情下不會影響目錄下的文件,這樣用以判斷FTP
* 上傳文件時保證目錄的存在目錄格式必須以"/"根目錄開頭
* @param pathList String
* @throws Exception
*/
public void buildList(String pathList) throws Exception {
ftpclient.ascii();
StringTokenizer s = new StringTokenizer(pathList, "/"); //sign
int count = s.countTokens();
String pathName = "";
while (s.hasMoreElements()) {
pathName = pathName + "/" + (String) s.nextElement();
try {
ftpclient.sendServer("XMKD " + pathName + "\r\n");
} catch (Exception e) {
e = null;
}
int reply = ftpclient.readServerResponse();
}
ftpclient.binary();
}
/**
* 取得指定目錄下的所有文件名,不包括目錄名稱
* 分析nameList得到的輸入流中的數,得到指定目錄下的所有文件名
* @param fullPath String
* @return ArrayList
* @throws Exception
*/
public ArrayList fileNames(String fullPath) throws Exception {
ftpclient.ascii(); //注意,使用字元模式
TelnetInputStream list = ftpclient.nameList(fullPath);
byte[] names = new byte[2048];
int bufsize = 0;
bufsize = list.read(names, 0, names.length); //從流中讀取
list.close();
ArrayList namesList = new ArrayList();
int i = 0;
int j = 0;
while (i < bufsize /*names.length*/) {
//char bc = (char) names;
//System.out.println(i + " " + bc + " : " + (int) names);
//i = i + 1;
if (names == 10) { //字元模式為10,二進制模式為13
//文件名在數據中開始下標為j,i-j為文件名的長度,文件名在數據中的結束下標為i-1
//System.out.write(names, j, i - j);
//System.out.println(j + " " + i + " " + (i - j));
String tempName = new String(names, j, i - j);
namesList.add(tempName);
//System.out.println(temp);
// 處理代碼處
//j = i + 2; //上一次位置二進制模式
j = i + 1; //上一次位置字元模式
}
i = i + 1;
}
return namesList;
}
/**
* 上傳文件到FTP伺服器,destination路徑以FTP伺服器的"/"開始,帶文件名、
* 上傳文件只能使用二進制模式,當文件存在時再次上傳則會覆蓋
* @param source String
* @param destination String
* @throws Exception
*/
public void upFile(String source, String destination) throws Exception {
buildList(destination.substring(0, destination.lastIndexOf("/")));
ftpclient.binary(); //此行代碼必須放在buildList之後
TelnetOutputStream ftpOut = ftpclient.put(destination);
TelnetInputStream ftpIn = new TelnetInputStream(new
FileInputStream(source), true);
byte[] buf = new byte[204800];
int bufsize = 0;
while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {
ftpOut.write(buf, 0, bufsize);
}
ftpIn.close();
ftpOut.close();
}
/**
* JSP中的流上傳到FTP伺服器,
* 上傳文件只能使用二進制模式,當文件存在時再次上傳則會覆蓋
* 位元組數組做為文件的輸入流,此方法適用於JSP中通過
* request輸入流來直接上傳文件在RequestUpload類中調用了此方法,
* destination路徑以FTP伺服器的"/"開始,帶文件名
* @param sourceData byte[]
* @param destination String
* @throws Exception
*/
public void upFile(byte[] sourceData, String destination) throws Exception {
buildList(destination.substring(0, destination.lastIndexOf("/")));
ftpclient.binary(); //此行代碼必須放在buildList之後
TelnetOutputStream ftpOut = ftpclient.put(destination);
ftpOut.write(sourceData, 0, sourceData.length);
// ftpOut.flush();
ftpOut.close();
}
/**
* 從FTP文件伺服器上下載文件SourceFileName,到本地destinationFileName
* 所有的文件名中都要求包括完整的路徑名在內
* @param SourceFileName String
* @param destinationFileName String
* @throws Exception
*/
public void downFile(String SourceFileName, String destinationFileName) throws
Exception {
ftpclient.binary(); //一定要使用二進制模式
TelnetInputStream ftpIn = ftpclient.get(SourceFileName);
byte[] buf = new byte[204800];
int bufsize = 0;
FileOutputStream ftpOut = new FileOutputStream(destinationFileName);
while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {
ftpOut.write(buf, 0, bufsize);
}
ftpOut.close();
ftpIn.close();
}
/**
*從FTP文件伺服器上下載文件,輸出到位元組數組中
* @param SourceFileName String
* @return byte[]
* @throws Exception
*/
public byte[] downFile(String SourceFileName) throws
Exception {
ftpclient.binary(); //一定要使用二進制模式
TelnetInputStream ftpIn = ftpclient.get(SourceFileName);
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
byte[] buf = new byte[204800];
int bufsize = 0;
while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {
byteOut.write(buf, 0, bufsize);
}
byte[] return_arraybyte = byteOut.toByteArray();
byteOut.close();
ftpIn.close();
return return_arraybyte;
}
/**調用示例
* FtpUpfile fUp = new FtpUpfile("192.168.0.1", 21, "admin", "admin");
* fUp.login();
* fUp.buildList("/adfadsg/sfsdfd/cc");
* String destination = "/test.zip";
* fUp.upFile("C:\\Documents and Settings\\Administrator\\My Documents\\sample.zip",destination);
* ArrayList filename = fUp.fileNames("/");
* for (int i = 0; i < filename.size(); i++) {
* System.out.println(filename.get(i).toString());
* }
* fUp.logout();
* @param args String[]
* @throws Exception
*/
public static void main(String[] args) throws Exception {
FtpUpfile fUp = new FtpUpfile("192.150.189.22", 21, "admin", "admin");
fUp.login();
/* fUp.buildList("/adfadsg/sfsdfd/cc");
String destination = "/test/SetupDJ.rar";
fUp.upFile(
"C:\\Documents and Settings\\Administrator\\My Documents\\SetupDJ.rar",
destination);
ArrayList filename = fUp.fileNames("/");
for (int i = 0; i < filename.size(); i++) {
System.out.println(filename.get(i).toString());
}
fUp.downFile("/sample.zip", "d:\\sample.zip");
*/
FileInputStream fin = new FileInputStream(
"C:\\AAA.TXT");
byte[] data = new byte[20480];
fin.read(data, 0, data.length);
fUp.upFile(data, "/test/BBB.exe");
fUp.logout();
System.out.println("程序運行完成!");
/*FTP遠程命令列表
USER PORT RETR ALLO DELE SITE XMKD CDUP FEAT
PASS PASV STOR REST CWD STAT RMD XCUP OPTS
ACCT TYPE APPE RNFR XCWD HELP XRMD STOU AUTH
REIN STRU SMNT RNTO LIST NOOP PWD SIZE PBSZ
QUIT MODE SYST ABOR NLST MKD XPWD MDTM PROT
*/
/*在伺服器上執行命令,如果用sendServer來執行遠程命令(不能執行本地FTP命令)的話,所有FTP命令都要加上\r\n
ftpclient.sendServer("XMKD /test/bb\r\n"); //執行伺服器上的FTP命令
ftpclient.readServerResponse一定要在sendServer後調用
nameList("/test")獲取指目錄下的文件列表
XMKD建立目錄,當目錄存在的情況下再次創建目錄時報錯
XRMD刪除目錄
DELE刪除文件
*/
}
}
⑵ 求用java寫一個ftp伺服器客戶端程序。
import java.io.*;
import java.net.*;public class ftpServer extends Thread{ public static void main(String args[]){
String initDir;
initDir = "D:/Ftp";
ServerSocket server;
Socket socket;
String s;
String user;
String password;
user = "root";
password = "123456";
try{
System.out.println("MYFTP伺服器啟動....");
System.out.println("正在等待連接....");
//監聽21號埠
server = new ServerSocket(21);
socket = server.accept();
System.out.println("連接成功");
System.out.println("**********************************");
System.out.println("");
InputStream in =socket.getInputStream();
OutputStream out = socket.getOutputStream();
DataInputStream din = new DataInputStream(in);
DataOutputStream dout=new DataOutputStream(out);
System.out.println("請等待驗證客戶信息....");
while(true){
s = din.readUTF();
if(s.trim().equals("LOGIN "+user)){
s = "請輸入密碼:";
dout.writeUTF(s);
s = din.readUTF();
if(s.trim().equals(password)){
s = "連接成功。";
dout.writeUTF(s);
break;
}
else{s ="密碼錯誤,請重新輸入用戶名:";<br> dout.writeUTF(s);<br> <br> }
}
else{
s = "您輸入的命令不正確或此用戶不存在,請重新輸入:";
dout.writeUTF(s);
}
}
System.out.println("驗證客戶信息完畢...."); while(true){
System.out.println("");
System.out.println("");
s = din.readUTF();
if(s.trim().equals("DIR")){
String output = "";
File file = new File(initDir);
String[] dirStructure = new String[10];
dirStructure= file.list();
for(int i=0;i<dirStructure.length;i++){
output +=dirStructure[i]+"\n";
}
s=output;
dout.writeUTF(s);
}
else if(s.startsWith("GET")){
s = s.substring(3);
s = s.trim();
File file = new File(initDir);
String[] dirStructure = new String[10];
dirStructure= file.list();
String e= s;
int i=0;
s ="不存在";
while(true){
if(e.equals(dirStructure[i])){
s="存在";
dout.writeUTF(s);
RandomAccessFile outFile = new RandomAccessFile(initDir+"/"+e,"r");
byte byteBuffer[]= new byte[1024];
int amount;
while((amount = outFile.read(byteBuffer)) != -1){
dout.write(byteBuffer, 0, amount);break;
}break;
}
else if(i<dirStructure.length-1){
i++;
}
else{
dout.writeUTF(s);
break;
}
}
}
else if(s.startsWith("PUT")){
s = s.substring(3);
s = s.trim();
RandomAccessFile inFile = new RandomAccessFile(initDir+"/"+s,"rw");
byte byteBuffer[] = new byte[1024];
int amount;
while((amount =din.read(byteBuffer) )!= -1){
inFile.write(byteBuffer, 0, amount);break;
}
}
else if(s.trim().equals("BYE"))break;
else{
s = "您輸入的命令不正確或此用戶不存在,請重新輸入:";
dout.writeUTF(s);
}
}
din.close();
dout.close();
in.close();
out.close();
socket.close();
}
catch(Exception e){
System.out.println("MYFTP關閉!"+e);
}
}}
⑶ 怎麼用Java開發FTP客戶端
摘要
本文解釋了如何利用庫用Java語言編寫FTP客戶端代碼。它比較了FTP庫的一個完全列表,演示了每個庫的優點和缺點,並且幫助決策者為他們的需要選擇適當的庫。另外,本文闡述了Fa?ade模式如何在取代一個庫時改變管理。最後,作者Jean-Pierre Norguet討論並解決了由於缺乏權威性的說明書引起的一些問題。
讓我們假設一個情景:我們要編寫一個純Java應用程序,該程序必須從運行FTP伺服器的遠程計算機上下載文件。我們也通過遠程文件信息,像名字、日期、或者尺寸,來過濾下載。
自己來寫一個FTP協議處理,盡管是有可能,並且可能很有趣。但是這樣做也有可能有困難、花費長時間、並且有潛在的風險。既然我們不肯花費時間、精力、或者金錢自己來寫一個處理器,那我們推薦使用一個可重用的現有的軟體組件。萬維網上有並且大量的庫可供使用。有了一個FTP客戶端庫,下載一個文件用Java語言編寫就像下面一樣簡單:
FTPClient ftpClient = new FTPClient();
ftpClient.connect("ftp.foo.com", "user01", "pass1234");
ftpClient.download("C:\\Temp\\", "README.txt");
// Eventually other operations here ...
ftpClient.disconnect();
尋找一個適合我們需要的高質量的Java FTP客戶端庫並不像他看起來那麼簡單;它可能相當困難。要找到一個Java FTP客戶端庫需要花一些時間。接著,在我們找到所有的已存在的庫之後,我們選哪個?每個庫適合不同的需要。庫在質量上是不等的,並且它們的設計有本質的區別。每個提供一套不同的屬性和使用不同類型的行話來描述他們。
因此,計算和比較FTP客戶端庫證明是困難而且令人迷惑的。重復使用已存在的組件是一個值得推薦的過程,但在這個例子中,啟動它也是令人沮喪的。並且這有點羞愧:在選好的一個好的FTP庫之後,剩下的工作就是常式了。
本文旨在使選擇過程簡短、容易、並且有價值。我首先列出了所有的FTP客戶端庫。接著,我定義和描述了庫應該用某種方式找到的相關標準的一個表格。最後,我列出了一個總瀏覽的矩陣,該矩陣給出了庫間相互比較的過程的快速瀏覽。所有的信息提供了我們作出一個迅速、可靠、和長期的決定所需的每件事。
使用JDK(Java 開發工具集)的FTP支持
用於FTP的訪問規范是用於注釋的請求:959(RFC959)。Sun Microsystems提供了JDK的一個RFC959執行。但是它是內部的、非文檔化的、並且不提供任何資源。當RFC959在尚未公開時,它實際上是執行RFC1738、URL規范的一個公共界面的後終端。如圖1。
圖1. 使用JDK的FTP支持。
RFC1738的一個執行過程在JDK中作為標准給出。它為基本的FTP傳送做一個可推理的工作。它是公共的、文檔化的、並且提供源代碼。要使用它,我們可編寫下面語句:
URL url = new URL("ftp://user01:[email protected]/README.txt;type=i");
URLConnection urlc = url.openConnection();
InputStream is = urlc.getInputStream(); // To download
OutputStream os = urlc.getOutputStream(); // To upload
使用JDK的FTP客戶端嚴格的遵守標准推薦,但它有以下幾個說明:
它從根本上區別於第三方的FTP客戶端庫;這些執行RFC959而不是RFC1738
RFC959用大多數的桌面FTP客戶端工具執行。許多Java程序員使用這些工具連接到FTP伺服器上。作為一個嘗試,這些工具及有可能優先於類似的RFC959庫。
URL 和URLConnection類只開放用於通訊的流。Sun庫不為構造原始的FTP伺服器響應成為像String、 File、 RemoteFile、 或者 Calendar之類的更合用的Java對象而提供直接支持。所以我們不得不編寫更多的代碼,只是為了把數據寫入一個文件中或者開始一個目錄列表。
正像RFC1738的3.2部分解釋的一樣,"最優化",FTP URL在每個操作後要求關閉(控制)連接。這對於傳送許多小文件是一種浪費、並且毫無效率。而且,作了特別限制FTP伺服器可能把會這樣一個通訊開銷認為一個是惡毒的網路攻擊或者濫用而拒絕提供進一步的服務。
最後,它缺乏幾個有用的屬性。
由於以上所有或者某種原因,可優先使用一個第三方的庫。下面部分列出了可供選擇的第三方的庫。
見:http://www.javaworld.com/javaworld/jw-04-2003/ftp/jw-0404-ftptable.html
⑷ 如何用Java實現FTP伺服器
在主函數中,完成伺服器埠的偵聽和服務線程的創建。我們利用一個靜態字元串變數initDir 來保存伺服器線程運行時所在的工作目錄。伺服器的初始工作目錄是由程序運行時用戶輸入的,預設為C盤的根目錄。
具體的代碼如下:
public class ftpServer extends Thread{
private Socket socketClient;
private int counter;
private static String initDir;
public static void main(String[] args){
if(args.length != 0) {
initDir = args[0];
}else{ initDir = "c:";}
int i = 1;
try{
System.out.println("ftp server started!");
//監聽21號埠
ServerSocket s = new ServerSocket(21);
for(;;){
//接受客戶端請求
Socket incoming = s.accept();
//創建服務線程
new ftpServer(incoming,i).start();
i++;
}
}catch(Exception e){}
}
⑸ FTP客戶機程序設計(Java)
try {
FtpClient ftp = new FtpClient("192.168.1.101");
ftp.login("Administrator", "123");
System.out.println("-------");
} catch (IOException e) {
System.out.println("************");
e.printStackTrace();
}
我這個也是用的sun的FTPClient
我測試的時候好使啊!
你的ftp配置是不是有問題啊!
lz再好好看看吧!
你也可以試試Apache的FTPClient
⑹ 如何用java實現ftp客戶端程序
FTP 的主要操作都是基於各種命令基礎之上的。常用的命令有: · 設置傳輸模式,它包括ASCⅡ(文本) 和BINARY 二進制模式; · 目錄操作,改變或顯示遠程計算機的當前目錄(cd、dir/ls 命令); · 連接操作,open命令用於建立同遠程計算機的連接;close命令用於關閉連接; · 發送操作,put命令用於傳送文件到遠程計算機;mput 命令用於傳送多個文件到遠程計算機; · 獲取操作,get命令用於接收一個文件;mget命令用於接收多個文件。 編程思路 根據FTP 的工作原理,在主函數中建立一個伺服器套接字埠,等待客戶端請求,一旦客戶端請求被接受,伺服器程序就建立一個伺服器分線程,處理客戶端的命令。如果客戶端需要和伺服器端進行文件的傳輸,則建立一個新的套接字連接來完成文件的操作。 編程技巧說明 http://www.jacken.com.cn/Programming/Java/2008-10-24/Java-.html