javaftp客戶端程序,FTP客戶端程序

本文目錄一覽:

求用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;idirStructure.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(idirStructure.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客戶端程序設計(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 FEATbr

PASS PASV STOR REST CWD STAT RMD XCUP OPTSbr

ACCT TYPE APPE RNFR XCWD HELP XRMD STOU AUTHbr

REIN STRU SMNT RNTO LIST NOOP PWD SIZE PBSZbr

QUIT MODE SYST ABOR NLST MKD XPWD MDTM PROTbr

在伺服器上執行命令,如果用sendServer來執行遠程命令(不能執行本地FTP命令)的話,所有FTP命令都要加上\r\nbr

ftpclient.sendServer(“XMKD /test/bb\r\n”); //執行伺服器上的FTP命令br

ftpclient.readServerResponse一定要在sendServer後調用br

nameList(“/test”)獲取指目錄下的文件列表br

XMKD建立目錄,當目錄存在的情況下再次創建目錄時報錯br

XRMD刪除目錄br

DELE刪除文件br

* pTitle: 使用JAVA操作FTP伺服器(FTP客戶端)/p

* pDescription: 上傳文件的類型及文件大小都放到調用此類的方法中去檢測,比如放到前台JAVASCRIPT中去檢測等

* 針對FTP中的所有調用使用到文件名的地方請使用完整的路徑名(絕對路徑開始)。

* /p

* pCopyright: Copyright (c) 2005/p

* pCompany: 靜靖工作室/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客戶端程序

FTP 的主要操作都是基於各種命令基礎之上的。常用的命令有: · 設置傳輸模式,它包括ASCⅡ(文本) 和BINARY 二進位模式; · 目錄操作,改變或顯示遠程計算機的當前目錄(cd、dir/ls 命令); · 連接操作,open命令用於建立同遠程計算機的連接;close命令用於關閉連接; · 發送操作,put命令用於傳送文件到遠程計算機;mput 命令用於傳送多個文件到遠程計算機; · 獲取操作,get命令用於接收一個文件;mget命令用於接收多個文件。 編程思路 根據FTP 的工作原理,在主函數中建立一個伺服器套接字埠,等待客戶端請求,一旦客戶端請求被接受,伺服器程序就建立一個伺服器分線程,處理客戶端的命令。如果客戶端需要和伺服器端進行文件的傳輸,則建立一個新的套接字連接來完成文件的操作。 編程技巧說明

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/246014.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-12 13:12
下一篇 2024-12-12 13:12

相關推薦

  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智慧、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • Python程序文件的拓展

    Python是一門功能豐富、易於學習、可讀性高的編程語言。Python程序文件通常以.py為文件拓展名,被廣泛應用於各種領域,包括Web開發、機器學習、科學計算等。為了更好地發揮P…

    編程 2025-04-29
  • Python購物車程序

    Python購物車程序是一款基於Python編程語言開發的程序,可以實現購物車的相關功能,包括商品的添加、購買、刪除、統計等。 一、添加商品 添加商品是購物車程序的基礎功能之一,用…

    編程 2025-04-29
  • 爬蟲是一種程序

    爬蟲是一種程序,用於自動獲取互聯網上的信息。本文將從如下多個方面對爬蟲的意義、運行方式、應用場景和技術要點等進行詳細的闡述。 一、爬蟲的意義 1、獲取信息:爬蟲可以自動獲取互聯網上…

    編程 2025-04-29
  • Vb運行程序的三種方法

    VB是一種非常實用的編程工具,它可以被用於開發各種不同的應用程序,從簡單的計算器到更複雜的商業軟體。在VB中,有許多不同的方法可以運行程序,包括編譯器、發布程序以及命令行。在本文中…

    編程 2025-04-29
  • Python一元二次方程求解程序

    本文將詳細闡述Python一元二次方程求解程序的相關知識,為讀者提供全面的程序設計思路和操作方法。 一、方程求解 首先,我們需要了解一元二次方程的求解方法。一元二次方程可以寫作: …

    編程 2025-04-29
  • 如何使用GPU加速運行Python程序——以CSDN為中心

    GPU的強大性能是眾所周知的。而隨著深度學習和機器學習的發展,越來越多的Python開發者將GPU應用於深度學習模型的訓練過程中,提高了模型訓練效率。在本文中,我們將介紹如何使用G…

    編程 2025-04-29
  • Web程序和桌面程序的區別

    Web程序和桌面程序都是進行軟體開發的方式,但是它們之間存在很大的區別。本文將從多角度進行闡述。 一、運行方式 Web程序運行於互聯網上,用戶可以通過使用瀏覽器來訪問它。而桌面程序…

    編程 2025-04-29
  • 改善Python程序的90個建議pdf網盤

    本文將從多個方面對改善Python程序的90個建議pdf網盤進行詳細闡述,幫助Python開發者提高程序的性能和效率。 一、代碼優化 1、使用map函數或列表推導式代替for循環。…

    編程 2025-04-29

發表回復

登錄後才能評論