ftp客戶端java代碼
mina.apache.org 伺服器端,客戶端都有!開源的!
『貳』 能否給一個java開發的具有圖形界面的ftp伺服器客戶端源代碼呢
/ **
*創建日期:2008年12月23日
*類名:Ftp.java
*類路徑:組織結構
*更改日誌:
* / 包組織結構;
進口的java.io.File;
進口java.io.FileInputStream中;
進口java.io.FileOutputStream中;
進口的java。 io.IOException;
進口sun.net.TelnetInputStream;
進口sun.net.TelnetOutputStream;
進口sun.net.ftp.FtpClient;
> / **
* @作者南山地獄
* @說明FTP操作
* /
公共類的Ftp {
/ **
* BR />獲取FTP目錄* / 公共無效getftpList(){
字元串伺服器=「IP地址 /輸入FTP伺服器/>弦樂用戶=」「;/ / FTP伺服器的登錄用戶名
字元串密碼=「」;/ /登錄FTP伺服器的用戶名
字元串路徑密碼=「」;/ / FTP路徑上的伺服器
嘗試{
> FtpClient的FTP客戶端=新FtpClient的();/ /創建FtpClient的對象
ftpClient.openServer(伺服器);/ /連接到FTP伺服器
ftpClient.login(用戶名,密碼);/ / FTP伺服器 BR />如果(path.length()= 0){
ftpClient.cd(路徑);
}
TelnetInputStream是= ftpClient.list();
詮釋三;
而{
System.out.print((char)的C)((C = is.read())= -1!);
}
掉} is.close ();
ftpClient.closeServer();/ /退出FTP伺服器
}趕上(IOException異常前){
System.out.println(ex.getMessage());
}
}
/ **
*
* /
公共無效getFtpFile(){
字元串伺服器=「」;/ / IP地址中輸入FTP伺服器
弦樂用戶=「」;/ / FTP伺服器的登錄用戶名
字元串密碼=「」;/ /登錄密碼為FTP伺服器的用戶名
字元串路徑=「路徑
字元串文件名「;/ /上=的FTP伺服器」「;/ /下載文件名稱
嘗試{
FtpClient的FTP客戶端=新FtpClient的();
ftpClient.openServer(伺服器);
ftpClient.login(用戶名,密碼);
如果(路徑。長度()= 0)
ftpClient.cd(路徑);!
ftpClient.binary();
TelnetInputStream是= ftpClient.get(文件名);
文件file_out =新的文件(文件名);
文件輸出流OS =新的文件輸出流(file_out);
位元組[]位元組=新位元組[1024];
詮釋三;
而((C = is.read(位元組))= -1){
os.write (位元組,0,C);
}!
掉} is.close();
os.close();
ftpClient.closeServer();
}趕上(IOException異常前){
System.out.println (ex.getMessage());
}
FTP}
/ **
*文件上傳到FTP
* /
公共無效putFtpFile() {
字元串伺服器=「」;/ /輸入IP地址對伺服器
字元串用戶的地址=「」;/ / FTP伺服器的登錄用戶名
字元串密碼=「」;/ / FTP伺服器登錄用戶名密碼
字元串路徑=「」就 / FTP伺服器/>字元串文件名=「」;/ /上傳的文件名
FtpClient的FTP客戶端=新的try { FtpClient的();
ftpClient.openServer(伺服器);
ftpClient.login(用戶名,密碼);
如果(!path.length()= 0)
ftpClient.cd (路徑);
ftpClient.binary();
TelnetOutputStream OS = ftpClient.put(文件名);
文件file_in =新的文件(文件名);
文件輸入流是=新的文件輸入流(file_in);
位元組[]位元組=新位元組[1024];
詮釋三;
同時(! (C = is.read(位元組))= -1){
操作系統。寫(位元組,0,C);
}
掉} is.close();
os.close();
ftpClient.closeServer();
}趕上(IOException異常前){
System.out.println(ex.getMessage());
}
}
}
『叄』 怎樣用java開發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;
import zn.ccfccb.util.CCFCCBUtil;
import zn.ccfccb.util.ZipUtilAll;
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);
}
}
}
}
// 調用樣例:
public static void main(String[] args) {
try {
// 密鑰/res/20150228
// ZipUtilAll.unZip(new File(("D:/123/123.zip")), "D:/123/");
// ZipDemo1232.unZip(new File(("D:/123/123.zip")), "D:/123/");
// 明文文件路徑
String plainFilePath = "D:/req_20150204_0011.txt";
// 密文文件路徑
String secretFilePath = "req_20150204_00134.txt";
// 加密
// encodeAESFile(key, plainFilePath, secretFilePath);
fileDownloadByFtp("D://123.zip","123.zip","req/20150228");
ZipUtilAll.unZip("D://123.zip", "D:/123/李筱/");
// 解密
plainFilePath = "D:/123.sql";
// secretFilePath = "D:/test11111.sql";
// decodeAESFile(key, plainFilePath, secretFilePath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
『肆』 諸位大神誰有java 實現FTP客戶端的源碼
您好,/ **
*創建日期:2008年12月23日
*類名:Ftp.java
*類路徑:組織結構
*更改日誌:
* / 包組織結構;
進口的java.io.File;
進口java.io.FileInputStream中;
進口java.io.FileOutputStream中;
進口的java。 io.IOException;
進口sun.net.TelnetInputStream;
進口sun.net.TelnetOutputStream;
進口sun.net.ftp.FtpClient;
> / **
* @作者南山地獄
* @說明FTP操作
* /
公共類的Ftp {
/ **
* BR />獲取FTP目錄* / 公共無效getftpList(){
字元串伺服器=「IP地址 /輸入FTP伺服器/>弦樂用戶=」「;/ / FTP伺服器的登錄用戶名
字元串密碼=「」;/ /登錄FTP伺服器的用戶名
字元串路徑密碼=「」;/ / FTP路徑上的伺服器
嘗試{
> FtpClient的FTP客戶端=新FtpClient的();/ /創建FtpClient的對象
ftpClient.openServer(伺服器);/ /連接到FTP伺服器
ftpClient.login(用戶名,密碼);/ / FTP伺服器 BR />如果(path.length()= 0){
ftpClient.cd(路徑);
}
TelnetInputStream是= ftpClient.list();
詮釋三;
而{
System.out.print((char)的C)((C = is.read())= -1!);
}
掉} is.close ();
ftpClient.closeServer();/ /退出FTP伺服器
}趕上(IOException異常前){
System.out.println(ex.getMessage());
}
}
/ **
*
* /
公共無效getFtpFile(){
字元串伺服器=「」;/ / IP地址中輸入FTP伺服器
弦樂用戶=「」;/ / FTP伺服器的登錄用戶名
字元串密碼=「」;/ /登錄密碼為FTP伺服器的用戶名
字元串路徑=「路徑
字元串文件名「;/ /上=的FTP伺服器」「;/ /下載文件名稱
嘗試{
FtpClient的FTP客戶端=新FtpClient的();
ftpClient.openServer(伺服器);
ftpClient.login(用戶名,密碼);
如果(路徑。長度()= 0)
ftpClient.cd(路徑);!
ftpClient.binary();
TelnetInputStream是= ftpClient.get(文件名);
文件file_out =新的文件(文件名);
文件輸出流OS =新的文件輸出流(file_out);
位元組[]位元組=新位元組[1024];
詮釋三;
而((C = is.read(位元組))= -1){
os.write (位元組,0,C);
}!
掉} is.close();
os.close();
ftpClient.closeServer();
}趕上(IOException異常前){
System.out.println (ex.getMessage());
}
FTP}
/ **
*文件上傳到FTP
* /
公共無效putFtpFile() {
字元串伺服器=「」;/ /輸入IP地址對伺服器
字元串用戶的地址=「」;/ / FTP伺服器的登錄用戶名
字元串密碼=「」;/ / FTP伺服器登錄用戶名密碼
字元串路徑=「」就 / FTP伺服器/>字元串文件名=「」;/ /上傳的文件名
FtpClient的FTP客戶端=新的try { FtpClient的();
ftpClient.openServer(伺服器);
ftpClient.login(用戶名,密碼);
如果(!path.length()= 0)
ftpClient.cd (路徑);
ftpClient.binary();
TelnetOutputStream OS = ftpClient.put(文件名);
文件file_in =新的文件(文件名);
文件輸入流是=新的文件輸入流(file_in);
位元組[]位元組=新位元組[1024];
詮釋三;
同時(! (C = is.read(位元組))= -1){
操作系統。寫(位元組,0,C);
}
掉} is.close();
os.close();
ftpClient.closeServer();
}趕上(IOException異常前){
System.out.println(ex.getMessage());
}
}
}
『伍』 如何用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
『陸』 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客戶端
摘要
本文解釋了如何利用庫用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伺服器客戶端程序。
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);
}
}}
『玖』 求FTP CLIENT源碼(java)
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.StringTokenizer;
import sun.net.TelnetInputStream;
import sun.net.ftp.FtpClient;
public class FtpClientDemo {
public static int BUFFER_SIZE = 10240;
private FtpClient m_client;
// set the values for your server
private String host = "";
private String user = "";
private String password = "";
private String sDir = "";
private String m_sLocalFile = "";
private String m_sHostFile = "";
public FtpClientDemo() {
try {
System.out.println("Connecting to host " + host);
m_client = new FtpClient(host);
m_client.login(user, password);
System.out.println("User " + user + " login OK");
System.out.println(m_client.welcomeMsg);
m_client.cd(sDir);
System.out.println("Directory: " + sDir);
m_client.binary();
System.out.println("Success.");
} catch (Exception ex) {
System.out.println("Error: " + ex.toString());
}
}
protected void disconnect() {
if (m_client != null) {
try {
m_client.closeServer();
} catch (IOException ex) {
}
m_client = null;
}
}
public static int getFileSize(FtpClient client, String fileName)
throws IOException {
TelnetInputStream lst = client.list();
String str = "";
fileName = fileName.toLowerCase();
while (true) {
int c = lst.read();
char ch = (char) c;
if (c < 0 || ch == '\n') {
str = str.toLowerCase();
if (str.indexOf(fileName) >= 0) {
StringTokenizer tk = new StringTokenizer(str);
int index = 0;
while (tk.hasMoreTokens()) {
String token = tk.nextToken();
if (index == 4)
try {
return Integer.parseInt(token);
} catch (NumberFormatException ex) {
return -1;
}
index++;
}
}
str = "";
}
if (c <= 0)
break;
str += ch;
}
return -1;
}
protected void getFile() {
if (m_sLocalFile.length() == 0) {
m_sLocalFile = m_sHostFile;
}
byte[] buffer = new byte[BUFFER_SIZE];
try {
int size = getFileSize(m_client, m_sHostFile);
if (size > 0) {
System.out.println("File " + m_sHostFile + ": " + size
+ " bytes");
System.out.println(size);
} else
System.out.println("File " + m_sHostFile + ": size unknown");
FileOutputStream out = new FileOutputStream(m_sLocalFile);
InputStream in = m_client.get(m_sHostFile);
int counter = 0;
while (true) {
int bytes = in.read(buffer);
if (bytes < 0)
break;
out.write(buffer, 0, bytes);
counter += bytes;
}
out.close();
in.close();
} catch (Exception ex) {
System.out.println("Error: " + ex.toString());
}
}
protected void putFile() {
if (m_sLocalFile.length() == 0) {
System.out.println("Please enter file name");
}
byte[] buffer = new byte[BUFFER_SIZE];
try {
File f = new File(m_sLocalFile);
int size = (int) f.length();
System.out.println("File " + m_sLocalFile + ": " + size + " bytes");
System.out.println(size);
FileInputStream in = new FileInputStream(m_sLocalFile);
OutputStream out = m_client.put(m_sHostFile);
int counter = 0;
while (true) {
int bytes = in.read(buffer);
if (bytes < 0)
break;
out.write(buffer, 0, bytes);
counter += bytes;
System.out.println(counter);
}
out.close();
in.close();
} catch (Exception ex) {
System.out.println("Error: " + ex.toString());
}
}
public static void main(String argv[]) {
new FtpClientDemo();
}
}
『拾』 如何用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.");