ftp封裝java
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);
}
}}
B. 如何用java連接到ftp上
現在已經封裝好了的方法,不需要任何其他知識即可連接的。只需要知道ftp登錄用戶名、密碼、埠、存儲路徑即可。
package zn.ccfccb.util;
import hkrt.b2b.view.util.Log;
import hkrt.b2b.view.util.ViewUtil;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class CCFCCBFTP {
/**
* 上傳文件
*
* @param fileName
* @param plainFilePath 明文文件路徑路徑
* @param filepath
* @return
* @throws Exception
*/
public static String fileUploadByFtp(String plainFilePath, String fileName, String filepath) throws Exception {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FTPClient ftpClient = new FTPClient();
String bl = "false";
try {
fis = new FileInputStream(plainFilePath);
bos = new ByteArrayOutputStream(fis.available());
byte[] buffer = new byte[1024];
int count = 0;
while ((count = fis.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
Log.info("加密上傳文件開始");
Log.info("連接遠程上傳伺服器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
// Log.info("連接遠程上傳伺服器"+"192.168.54.106:"+2021);
// ftpClient.connect("192.168.54.106", 2021);
// ftpClient.login("hkrt-CCFCCBHK", "3OLJheziiKnkVcu7Sigz");
FTPFile[] fs;
fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(filepath)) {
bl="true";
ftpClient.changeWorkingDirectory("/"+filepath+"");
}
}
Log.info("檢查文件路徑是否存在:/"+filepath);
if("false".equals(bl)){
ViewUtil.dataSEErrorPerformedCommon( "查詢文件路徑不存在:"+"/"+filepath);
return bl;
}
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
// 設置文件類型(二進制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile(fileName, fis);
Log.info("上傳文件成功:"+fileName+"。文件保存路徑:"+"/"+filepath+"/");
return bl;
} catch (Exception e) {
throw e;
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (bos != null) {
try {
bos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
}
}
/**
*下載並解壓文件
*
* @param localFilePath
* @param fileName
* @param routeFilepath
* @return
* @throws Exception
*/
public static String fileDownloadByFtp(String localFilePath, String fileName,String routeFilepath) throws Exception {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FileOutputStream fos = null;
FTPClient ftpClient = new FTPClient();
String SFP = System.getProperty("file.separator");
String bl = "false";
try {
Log.info("下載並解密文件開始");
Log.info("連接遠程下載伺服器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
// ftpClient.connect(CMBCUtil.CMBCHOSTNAME, 2021);
// ftpClient.login(CMBCUtil.CMBCLOGINNAME, CMBCUtil.CMBCLOGINPASSWORD);
FTPFile[] fs;
ftpClient.makeDirectory(routeFilepath);
ftpClient.changeWorkingDirectory(routeFilepath);
bl = "false";
fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
bl = "true";
Log.info("下載文件開始。");
ftpClient.setBufferSize(1024);
// 設置文件類型(二進制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
InputStream is = ftpClient.retrieveFileStream(fileName);
bos = new ByteArrayOutputStream(is.available());
byte[] buffer = new byte[1024];
int count = 0;
while ((count = is.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
fos = new FileOutputStream(localFilePath+SFP+fileName);
fos.write(bos.toByteArray());
Log.info("下載文件結束:"+localFilePath);
}
}
Log.info("檢查文件是否存:"+fileName+" "+bl);
if("false".equals(bl)){
ViewUtil.dataSEErrorPerformedCommon("查詢無結果,請稍後再查詢。");
return bl;
}
return bl;
} catch (Exception e) {
throw e;
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (bos != null) {
try {
bos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
C. JAVA 如何實現FTP遠程路徑
package nc.ui.doc.doc_007;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import nc.itf.doc.DocDelegator;
import nc.vo.doc.doc_007.DirVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.SuperVO;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTP;
public class FtpTool {
private FTPClient ftp;
private String romateDir = "";
private String userName = "";
private String password = "";
private String host = "";
private String port = "21";
public FtpTool(String url) throws IOException {
//String url="ftp://user:password@ip:port/ftptest/psd";
int len = url.indexOf("//");
String strTemp = url.substring(len + 2);
len = strTemp.indexOf(":");
userName = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
len = strTemp.indexOf("@");
password = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
host = "";
len = strTemp.indexOf(":");
if (len < 0)//沒有設置埠
{
port = "21";
len = strTemp.indexOf("/");
if (len > -1) {
host = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
} else {
strTemp = "";
}
} else {
host = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
len = strTemp.indexOf("/");
if (len > -1) {
port = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
} else {
port = "21";
strTemp = "";
}
}
romateDir = strTemp;
ftp = new FTPClient();
ftp.connect(host, FormatStringToInt(port));
}
public FtpTool(String host, int port) throws IOException {
ftp = new FTPClient();
ftp.connect(host, port);
}
public String login(String username, String password) throws IOException {
this.ftp.login(username, password);
return this.ftp.getReplyString();
}
public String login() throws IOException {
this.ftp.login(userName, password);
System.out.println("ftp用戶: " + userName);
System.out.println("ftp密碼: " + password);
if (!romateDir.equals(""))
System.out.println("cd " + romateDir);
ftp.changeWorkingDirectory(romateDir);
return this.ftp.getReplyString();
}
public boolean upload(String pathname, String filename) throws IOException, BusinessException {
int reply;
int j;
String m_sfilename = null;
filename = CheckNullString(filename);
if (filename.equals(""))
return false;
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.out.println("FTP server refused connection.");
System.exit(1);
}
FileInputStream is = null;
try {
File file_in;
if (pathname.endsWith(File.separator)) {
file_in = new File(pathname + filename);
} else {
file_in = new File(pathname + File.separator + filename);
}
if (file_in.length() == 0) {
System.out.println("上傳文件為空!");
return false;
}
//產生隨機數最大到99
j = (int)(Math.random()*100);
m_sfilename = String.valueOf(j) + ".pdf"; // 生成的文件名
is = new FileInputStream(file_in);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.storeFile(m_sfilename, is);
ftp.logout();
} finally {
if (is != null) {
is.close();
}
}
System.out.println("上傳文件成功!");
return true;
}
public boolean delete(String filename) throws IOException {
FileInputStream is = null;
boolean retValue = false;
try {
retValue = ftp.deleteFile(filename);
ftp.logout();
} finally {
if (is != null) {
is.close();
}
}
return retValue;
}
public void close() {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static int FormatStringToInt(String p_String) {
int intRe = 0;
if (p_String != null) {
if (!p_String.trim().equals("")) {
try {
intRe = Integer.parseInt(p_String);
} catch (Exception ex) {
}
}
}
return intRe;
}
public static String CheckNullString(String p_String) {
if (p_String == null)
return "";
else
return p_String;
}
public boolean downfile(String pathname, String filename) {
String outputFileName = null;
boolean retValue = false;
try {
FTPFile files[] = ftp.listFiles();
int reply = ftp.getReplyCode();
////////////////////////////////////////////////
if (!FTPReply.isPositiveCompletion(reply)) {
try {
throw new Exception("Unable to get list of files to dowload.");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/////////////////////////////////////////////////////
if (files.length == 0) {
System.out.println("No files are available for download.");
}else {
for (int i=0; i <files.length; i++) {
System.out.println("Downloading file "+files[i].getName()+"Size:"+files[i].getSize());
outputFileName = pathname + filename + ".pdf";
//return outputFileName;
File f = new File(outputFileName);
//////////////////////////////////////////////////////
retValue = ftp.retrieveFile(outputFileName, new FileOutputStream(f));
if (!retValue) {
try {
throw new Exception ("Downloading of remote file"+files[i].getName()+" failed. ftp.retrieveFile() returned false.");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/////////////////////////////////////////////////////////////
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retValue;
}
}
D. 用Java實現FTP伺服器解決方案
FTP 命令 FTP 的主要操作都是基於各種命令基礎之上的 常用的命令有 · 設置傳輸模式 它包括ASCⅡ(文本) 和BINARY 二進制模式;· 目錄操作 改變或顯示遠程計算機的當前目錄(cd dir/ls 命令);· 連接操作 open命令用於建立同遠程計算機的連接 close命令用於關閉連接;· 發送操作 put命令用於傳送文件到遠程計算機 mput 命令用於傳送多滾隱個文件到遠程計算機;· 獲取操作 get命令用於接收一個文件 mget命令用於接收多個文件 編程思路 根據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 != ) {initDir = args[ ];}else{ initDir = c: ;}int i = ;try{System out println( ftp server started! );//監聽 號埠ServerSocket s = new ServerSocket( );for(;;){//接受客戶端請求Socket ining = s accept();//創建服務御尺線程new ftpServer(ining i) start();i++;}}catch(Exception e){}} 線程類的設計線程類的主要設計都是在run()方法中實現 用run()方法得到客戶端的套接字信息 根據套接字得到輸入流和輸出流 向客戶端發送歡迎信息 FTP 命令的處理( ) 訪問控制命令· user name(user) 和 password (pass) 命令處理代碼如下 if(str startsWith( USER )){user = str substring( );user = user trim();out println( Password );}if(str startsWith( PASS ))out println( User +user+ logged in );User 命令和 Password 命令分別用來提交客戶端用戶輸入的用戶名和口令 · CWD (CHANGE WORKING DIRECTORY) 命令處理代碼如下 if(str startsWith( CWD )){String str = str substring( );dir = dir+ / +str trim();out println( CWD mand succesful );}該命令改變工作目錄到用戶指定的目錄 · CDUP (CHANGE TO PARENT DIRECTORY) 命令處理代碼如下 if(str startsWith( CDUP )){int n = dir lastIndexOf( / );dir = dir substring( n);out println( CWD mand succesful );}該命令改變當前目錄為上一層目錄大拆廳 · QUIT命令處理代碼如下 if(str startsWith( QUIT )) {out println( GOOD BYE );done = true;}該命令退出及關閉與伺服器的連接 輸出GOOD BYE ( ) 傳輸參數命令· Port命令處理代碼如下 if(str startsWith( PORT )) {out println( PORT mand successful );int i = str length() ;int j = str lastIndexOf( );int k = str lastIndexOf( j );String str str ;str = ;str = ;for(int l=k+ ;lstr = str + str charAt(l);}for(int l=j+ ;l<=i;l++){str = str + str charAt(l);}tempPort = Integer parseInt(str ) * * +Integer parseInt(str );}使用該命令時 客戶端必須發送客戶端用於接收數據的 位IP 地址和 位 的TCP 埠號 這些信息以 位為一組 使用十進制傳輸 中間用逗號隔開 · TYPE命令處理代碼如下 if(str startsWith( TYPE )){out println( type set );}TYPE 命令用來完成類型設置 ( ) FTP 服務命令· RETR (RETEIEVE) 和 STORE (STORE)命令處理的代碼if(str startsWith( RETR )){out println( Binary data connection );str = str substring( );str = str trim();RandomAccessFile outFile = newRandomAccessFile(dir+ / +str r );Socket tempSocket = new Socket(host tempPort);OutputStream outSocket = tempSocket getOutputStream();byte byteBuffer[]= new byte[ ];int amount;try{while((amount = outFile read(byteBuffer)) != ){outSocket write(byteBuffer amount);}outSocket close();out println( transfer plete );outFile close();tempSocket close();}catch(IOException e){}}if(str startsWith( STOR )){out println( Binary data connection );str = str substring( );str = str trim();RandomAccessFile inFile = newRandomAccessFile(dir+ / +str rw );Socket tempSocket = new Socket(host tempPort);InputStream inSocket = tempSocket getInputStream();byte byteBuffer[] = new byte[ ];int amount;try{while((amount =inSocket read(byteBuffer) )!= ){inFile write(byteBuffer amount);}inSocket close();out println( transfer plete );inFile close();tempSocket close();}catch(IOException e){}}文件傳輸命令包括從伺服器中獲得文件RETR和向伺服器中發送文件STOR 這兩個命令的處理非常類似 處理RETR命令時 首先得到用戶要獲得的文件的名稱 根據名稱創建一個文件輸入流 然後和客戶端建立臨時套接字連接 並得到一個輸出流 隨後 將文件輸入流中的數據讀出並藉助於套接字輸出流發送到客戶端 傳輸完畢以後 關閉流和臨時套接字 STOR 命令的處理也是同樣的過程 只是方向正好相反 · DELE (DELETE)命令處理代碼如下 if(str startsWith( DELE )){str = str substring( );str = str trim();File file = new File(dir str);boolean del = file delete();out println( delete mand successful );}DELE 命令用於刪除伺服器上的指定文件 · LIST命令處理代碼如下 if(str startsWith( LIST )) {try{out println( ASCII data );Socket tempSocket = new Socket(host tempPort);PrintWriter out = new PrintWriter(tempSocket getOutputStream() true);File file = new File(dir);String[] dirStructure = new String[ ];dirStructure= file list();String strType= ;for(int i= ;iif( dirStructure[i] indexOf( ) == ) { strType = d ;}else{strType = ;}out println(strType+dirStructure[i]);}tempSocket close();out println( transfer plete );}catch(IOException e){}LIST 命令用於向客戶端返回伺服器中工作目錄下的目錄結構 包括文件和目錄的列表 處理這個命令時 先創建一個臨時的套接字向客戶端發送目錄信息 這個套接字的目的埠號預設為 然後為當前工作目錄創建File 對象 利用該對象的list()方法得到一個包含該目錄下所有文件和子目錄名稱的字元串數組 然後根據名稱中是否含有文件名中特有的 來區別目錄和文件 最後 將得到的名稱數組通過臨時套接字發送到客戶端 lishixin/Article/program/Java/JSP/201311/19211
E. 用java實現sftp的客戶端,channel.connect()的時候,拋出異常,收到信息過長,然後就沒連上。怎麼回事
首先,不太明確你要問什麼?
J2EE是java企業級應用,它裡面關於安全方面的東西很多!
許可權管理?信息安全?授權服務?訪問控制?數據機密性?
要是你想全部都了解!
在這里提問是不行的!太龐雜了!
如果 你要問的是 java ftp傳輸過程中的一些安全注意事項!
這里建議 你使用 apache的開源項目。他們把基於java的ftp操作都封裝好了!
安全相關都有保證。
我下面可以給你復制一段 ftp下載遠程終端的java代碼!你可以參考一下!
需要下載 org.apache.commons.net包
可以到 網站下載!
/**
* Description: 從FTP伺服器下載文件
* @param ip FTP伺服器的ip地址
* @param port FTP伺服器埠,默認為:21
* @param username FTP登錄賬號
* @param password FTP登錄密碼
* @param remotePath FTP伺服器上的相對路徑
* @param fileName 要下載的文件名
* @param localPath 下載後保存到本地的路徑
* @return
*/
public static boolean downFile(String ip, int port,String username, String password, String remotePath,String fileName,String localPath,String localfile) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(ip, port);
//處理中文轉碼操作
ftp.setControlEncoding("GBK");
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");
ftp.login(username, password);//登錄
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(remotePath);//轉移到FTP伺服器目錄
FTPFile[] fs = ftp.listFiles();
for(int i = 0; i < fs.length; i++){
FTPFile ff = fs[i];
if(ff.getName().equals(fileName)){
String localfilename = localfile;//按規則設置文件名這里你要下載文件,可以自己定義下載之後的文件名
File localFile = new File(localPath+File.separator+localfilename);
OutputStream is = new FileOutputStream(localFile);
//此處retrieveFile的第一個參數由GBK轉為ISO-8859-1編碼。否則下載後的文件內容為空。
ftp.retrieveFile(new String(ff.getName().getBytes("GBK"),"ISO-8859-1"), is);
is.close();
}
}
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
F. java做ftp伺服器需要什麼jar包
apache的包:commons-net.jar
主要使用到的類:
org.apache.commons.net.ftp.FTPClient;
org.apache.commons.net.ftp.FTPFile;
org.apache.commons.net.ftp.FTPReply;
JDK中也有自帶的ftp包:
sun.net.ftp.下有FTP操作類
但sun已經不建議使用了, 建議樓主使用apache的包
G. java ftp 有哪些工具類
java ftp 最常用的是apache commons-net
commons-net項目中封裝了各種網路協議的客戶端,支持的協議包括:
FTP
NNTP
SMTP
POP3
Telnet
TFTP
Finger
Whois
rexec/rcmd/rlogin
Time (rdate) and Daytime
Echo
Discard
NTP/SNTP
其他的還有FTP4J ,jftp
H. 如何用Java實現FTP伺服器
FTP(File Transfer Protocol 文件傳輸協議)是Internet 上用來傳送文件的協議。在Internet上通過FTP 伺服器可以進行文件的上傳(Upload)或下載(Download)。FTP是實時聯機服務,在使用它之前必須是具有該服務的一個用戶(用戶名和口令),工作時客戶端必須先登錄到作為伺服器一方的計算機上,用戶登錄後可以進行文件搜索和文件傳送等有關操作,如改變當前工作目錄、列文件目錄、設置傳輸參數及傳送文件等。使用FTP可以傳送所有類型的文件,如文本文件、二進制可執行文件、圖象文件、聲音文件和數據壓縮文件等。
FTP 命令
FTP 的主要操作都是基於各種命令基礎之上的。常用的命令有:
設置傳輸模式,它包括ASCⅡ(文本) 和BINARY 二進制模式;
目錄操作,改變或顯示遠程計算機的當前目錄(cd、dir/ls 命令);
連接操作,open命令用於建立同遠程計算機的連接;close命令用於關閉連接;
發送操作,put命令用於傳送文件到遠程計算機;mput 命令用於傳送多個文件到遠程計算機;
獲取操作,get命令用於接收一個文件;mget命令用於接收多個文件。
?
import java.net.Socket;import org.apache.log4j.Logger;/** * 角色——伺服器A * @author Leon * */public class ServerA{ public static void main(String[] args){ final String F_DIR = "c:/test";//根路徑 final int PORT = 22;//監聽埠號 Logger.getRootLogger(); Logger logger = Logger.getLogger("com"); try{ ServerSocket s = new ServerSocket(PORT); logger.info("Connecting to server A..."); logger.info("Connected Successful! Local Port:"+s.getLocalPort()+". Default Directory:'"+F_DIR+"'."); while( true ){ //接受客戶端請求 Socket client = s.accept(); //創建服務線程 new ClientThread(client, F_DIR).start(); } } catch(Exception e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } }}import java.io.BufferedReader; import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.PrintWriter;import java.io.RandomAccessFile;import java.net.ConnectException;import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket;import java.net.UnknownHostException;import java.nio.charset.Charset;import java.util.Random;import org.apache.log4j.Logger;/** * 客戶端子線程類 * @author Leon * */public class ClientThread extends Thread { private Socket socketClient;//客戶端socket private Logger logger;//日誌對象 private String dir;//絕對路徑 private String pdir = "/";//相對路徑 private final static Random generator = new Random();//隨機數 public ClientThread(Socket client, String F_DIR){ this.socketClient = client; this.dir = F_DIR; } @Override public void run() { Logger.getRootLogger(); logger = Logger.getLogger("com"); InputStream is = null; OutputStream os = null; try { is = socketClient.getInputStream(); os = socketClient.getOutputStream(); } catch (IOException e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); PrintWriter pw = new PrintWriter(os); String clientIp = socketClient.getInetAddress().toString().substring(1);//記錄客戶端IP String username = "not logged in";//用戶名 String password = "";//口令 String command = "";//命令 boolean loginStuts = false;//登錄狀態 final String LOGIN_WARNING = "530 Please log in with USER and PASS first."; String str = "";//命令內容字元串 int port_high = 0; int port_low = 0; String retr_ip = "";//接收文件的IP地址 Socket tempsocket = null; //列印歡迎信息 pw.println("220-FTP Server A version 1.0 written by Leon Guo"); pw.flush(); logger.info("("+username+") ("+clientIp+")> Connected, sending welcome message..."); logger.info("("+username+") ("+clientIp+")> 220-FTP Server A version 1.0 written by Leon Guo"); boolean b = true; while ( b ){ try { //獲取用戶輸入的命令 command = br.readLine(); if(null == command) break; } catch (IOException e) { pw.println("331 Failed to get command"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 331 Failed to get command"); logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } b = false; } /* * 訪問控制命令 */ // USER命令 if(command.toUpperCase().startsWith("USER")){ logger.info("(not logged in) ("+clientIp+")> "+command); username = command.substring(4).trim(); if("".equals(username)){ pw.println("501 Syntax error"); pw.flush(); logger.info("(not logged in) ("+clientIp+")> 501 Syntax error"); username = "not logged in"; } else{ pw.println("331 Password required for " + username); pw.flush(); logger.info("(not logged in) ("+clientIp+")> 331 Password required for " + username); } loginStuts = false; } //end USER // PASS命令 else if(command.toUpperCase().startsWith("PASS")){ logger.info("(not logged in) ("+clientIp+")> "+command); password = command.substring(4).trim(); if(username.equals("root") && password.equals("root")){ pw.println("230 Logged on"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 230 Logged on");// logger.info("客戶端 "+clientIp+" 通過 "+username+"用戶登錄"); loginStuts = true; } else{ pw.println("530 Login or password incorrect!"); pw.flush(); logger.info("(not logged in) ("+clientIp+")> 530 Login or password incorrect!"); username = "not logged in"; } } //end PASS // PWD命令 else if(command.toUpperCase().startsWith("PWD")){ logger.info("("+username+") ("+clientIp+")> "+command); if(loginStuts){// logger.info("用戶"+clientIp+":"+username+"執行PWD命令"); pw.println("257 /""+pdir+"/" is current directory"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 257 /""+pdir+"/" is current directory"); } else{ pw.println(LOGIN_WARNING); pw.flush(); logger.info("("+username+") ("+clientIp+")> "+LOGIN_WARNING); } } //end PWD // CWD命令 else if(command.toUpperCase().startsWith("CWD")){ logger.info("("+username+") ("+clientIp+")> "+command); if(loginStuts){ str = command.substring(3).trim(); if("".equals(str)){ pw.println("250 Broken client detected, missing argument to CWD. /""+pdir+"/" is current directory."); pw.flush(); logger.info("("+username+") ("+clientIp+")> 250 Broken client detected, missing argument to CWD. /""+pdir+"/" is current directory."); } else{ //判斷目錄是否存在 String tmpDir = dir + "/" + str; File file = new File(tmpDir); if(file.exists()){//目錄存在 dir = dir + "/" + str; if("/".equals(pdir)){ pdir = pdir + str; } else{ pdir = pdir + "/" + str; }// logger.info("用戶"+clientIp+":"+username+"執行CWD命令"); pw.println("250 CWD successful. /""+pdir+"/" is current directory"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 250 CWD successful. /""+pdir+"/" is current directory"); } else{//目錄不存在 pw.println("550 CWD failed. /""+pdir+"/": directory not found."); pw.flush(); logger.info("("+username+") ("+clientIp+")> 550 CWD failed. /""+pdir+"/": directory not found.");