當前位置:首頁 » 文件管理 » ftp復制java

ftp復制java

發布時間: 2022-09-28 20:38:23

⑴ 用java怎麼獲取ftp上的文件

public class FtpClientUtil {
FtpClient ftpClient;
private String server;
private int port;
private String userName;
private String userPassword;

public FtpClientUtil(String server,int port,String userName,String userPassword)
{
this.server=server;
this.port=port;
this.userName=userName;
this.userPassword=userPassword;
}
/**
* 鏈接到伺服器
* @return
*/
public boolean open()
{
if(ftpClient!=null&&ftpClient.serverIsOpen())
return true;
try
{
ftpClient= new FtpClient();
ftpClient.openServer(server,port);
ftpClient.login(userName, userPassword);
ftpClient.binary();
return true;
}
catch(Exception e)
{
e.printStackTrace();
ftpClient=null;
return false;
}
}

public boolean cd(String dir){
boolean f = false;
try {
ftpClient.cd(dir);
} catch (IOException e) {
Logs.error(e.toString());
return f;
}
return true;
}

/**
* 上傳文件到FTP伺服器
* @param localPathAndFileName 本地文件目錄和文件名
* @param ftpFileName 上傳後的文件名
* @param ftpDirectory FTP目錄如:/path1/pathb2/,如果目錄不存在回自動創建目錄
* @throws Exception
*/
public boolean upload(String localDirectoryAndFileName,String ftpFileName,String ftpDirectory)throws Exception {
if(!open())
return false;
FileInputStream is=null;
TelnetOutputStream os=null;
try
{
char ch = ' ';
if (ftpDirectory.length() > 0)
ch = ftpDirectory.charAt(ftpDirectory.length() - 1);
for (; ch == '/' || ch == '\\'; ch = ftpDirectory.charAt(ftpDirectory.length() - 1))
ftpDirectory = ftpDirectory.substring(0, ftpDirectory.length() - 1);

int slashIndex = ftpDirectory.indexOf(47);
int backslashIndex = ftpDirectory.indexOf(92);
int index = slashIndex;
String dirall = ftpDirectory;
if (backslashIndex != -1 && (index == -1 || index > backslashIndex))
index = backslashIndex;
String directory = "";
while (index != -1) {
if (index > 0) {
String dir = dirall.substring(0, index);
directory = directory + "/" + dir;
ftpClient.sendServer("XMKD " + directory + "\r\n");
ftpClient.readServerResponse();
}
dirall = dirall.substring(index + 1);
slashIndex = dirall.indexOf(47);
backslashIndex = dirall.indexOf(92);
index = slashIndex;
if (backslashIndex != -1 && (index == -1 || index > backslashIndex))
index = backslashIndex;
}
ftpClient.sendServer("XMKD " + ftpDirectory + "\r\n");
ftpClient.readServerResponse();

os = ftpClient.put(ftpDirectory + "/"
+ ftpFileName);
File file_in = new File(localDirectoryAndFileName);
is = new FileInputStream(file_in);
byte bytes[] = new byte[1024];
int i;
while ((i = is.read(bytes)) != -1)
os.write(bytes, 0, i);
//清理垃圾

return true;
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
finally
{
if (is != null)
is.close();
if (os != null)
os.close();
}
}
/**
* 從FTP伺服器上下載文件並返回下載文件長度
* @param ftpDirectoryAndFileName
* @param localDirectoryAndFileName
* @return
* @throws Exception
*/
public long download(String ftpDirectoryAndFileName,String localDirectoryAndFileName)throws Exception
{
long result = 0;
if(!open())
return result;
TelnetInputStream is = null;
FileOutputStream os = null;
try
{
is = ftpClient.get(ftpDirectoryAndFileName);
java.io.File outfile = new java.io.File(localDirectoryAndFileName);
os = new FileOutputStream(outfile);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1)
{
os.write(bytes, 0, c);
result = result + c;
}
}
catch (Exception e)
{
throw e;
}
finally
{
if (is != null)
is.close();
if (os != null)
os.close();

}
return result;
}
/**
* 返回FTP目錄下的文件列表
* @param ftpDirectory
* @return
*/
public List<String> getFileNameList(String ftpDirectory)
{
List<String> list = new ArrayList<String>();
if(!open())
return list;
try
{
DataInputStream dis = new DataInputStream(ftpClient.nameList(ftpDirectory));
String filename = "";
while((filename=dis.readLine())!=null)
{
list.add(filename);
}
} catch (Exception e)
{
e.printStackTrace();
}
return list;
}
/**
* 刪除FTP上的文件
* @param ftpDirAndFileName
*/
public boolean deleteFile(String ftpDirAndFileName)
{
if(!open())
return false;
ftpClient.sendServer("DELE "+ftpDirAndFileName+"\r\n");
return true;
}
/**
* 刪除FTP目錄
* @param ftpDirectory
*/
public boolean deleteDirectory(String ftpDirectory)
{
if(!open())
return false;
ftpClient.sendServer("XRMD "+ftpDirectory+"\r\n");
return true;
}
/**
* 關閉鏈接
*/
public void close()
{
try
{
if(ftpClient!=null&&ftpClient.serverIsOpen())
ftpClient.closeServer();
}catch(Exception e)
{

}
}
}望採納,謝謝。

⑵ java中怎麼實現ftp文件傳輸

packagecom.quantongfu.ftp.ftp;

importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.net.ServerSocket;
importjava.util.List;

importorg.apache.commons.net.ftp.FTPReply;
importorg.apache.log4j.Logger;
importorg.apache.log4j.net.SocketServer;

importcom.quantongfu.conf.FtpConf;

/**
*@項目名稱:telinSyslog
*@文件名稱:Ftp.java
*@創建日期:2015年9月14日下午3:22:08
*@功能描述:ftp實體類,用於連接,上傳
*@修訂記錄:
*/
publicclassFtp{
privatestaticLoggerlogger=Logger.getLogger(Ftp.class);
privateFTPClientftp;

/**
*
*@parampath
*上傳到ftp伺服器哪個路徑下
*@paramaddr
*地址
*@paramport
*埠號
*@paramusername
*用戶名
*@parampassword
*密碼
*@return
*@throwsException
*/
publicbooleanconnect()throwsException{
booleanresult=false;
ftp=newFTPClient();
intreply;
ftp.connect(FtpConf.FTP_HOST,FtpConf.FTP_PORT);
ftp.login(FtpConf.FTP_USER_NAME,FtpConf.FTP_PASSWORD);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.setDataTimeout(60000);
reply=ftp.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){
ftp.disconnect();
returnresult;
}
if(FtpConf.IS_FTP_DIRECTORY){
ftp.changeWorkingDirectory(FtpConf.FTP_DIRECTORY);
}
result=true;
returnresult;
}

/**
*
*@paramfiles
*上傳的文件
*@throwsException
*/
publicbooleanupload(Filefile)throwsIOException{
FileInputStreaminput=null;
try{
input=newFileInputStream(file);
booleanb=ftp.storeFile(file.getName()+".tmp",input);
if(b){
b=ftp.rename(file.getName()+".tmp",file.getName());
}
returnb;
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}finally{
if(input!=null){
input.close();
}
}
}

/**
*
*@paramfiles
*上傳的文件
*@throwsException
*/
publicbooleanupload(ServerSocketserver,Filefile)throwsException{
FileInputStreaminput=null;
try{
if(!file.exists()){
returntrue;
}
input=newFileInputStream(file);
booleanb=ftp.storeFile(server,file.getName()+".tmp",input);
if(b){
b=ftp.rename(file.getName()+".tmp",file.getName());
if(b){
file.delete();
}
}
returnb;
}catch(Exceptione){
logger.error("ftperror"+e.getMessage());
returnfalse;
}finally{
if(input!=null){
try{
input.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}
/*斷開連接*/
publicvoiddisConnect(){
try{
if(ftp!=null){
ftp.disconnect();
}
}catch(IOExceptione){
e.printStackTrace();
}

}
/*獲取連接*/
publicstaticFtpgetFtp(){
Ftpftp=newFtp();
try{
ftp.connect();
}catch(Exceptione){
logger.error("FTP連接異常"+e.getMessage());
e.printStackTrace();
}
returnftp;
}
/*重連*/
publicFtpreconnect(){
disConnect();
returngetFtp();
}
}

使用Apache FtpClient jar包,獲取jar : http://commons.apache.org/net/

⑶ 我想登錄一個ftp然後把某個目錄的所有文件考到另一個ftp的目錄的某個文件夾下用java代碼實現

用的commons-net包中的FTPClient
ftp1為拷貝目錄,ftp2為被拷貝目錄
你先登錄ftp2調用ftp1,
ftpClient1.changeWorkingDirectory(path);
InputStream inputStream = ftpClient1.retrieveFileStream(file.getName());
用這個代碼應該可以從ftp1中獲得一個inputStream ,在ftp2中可以做上傳操作
目錄的話ftp2還要做遞歸存放到list中,ftp2遍歷上傳. 其實我也沒做這個,希望思路有點幫助,應該可以實現.good luck!~~~

⑷ FTP 復制文件命令

FTP 復制文件命令是get 文件名
1) 說明:顯示ftp命令的說明。後面可以加參數,是加需要解釋的命令名,不加則顯示包含所有命令列表。
2)說明:功能是在本地計算機上運行指定命令。
如! command 其中command就是你要運行的命令,如果不加command這個參數的話,則顯示本地命令提示, 這時你輸入exit命令就能返回到ftp了。
3)$ macro-ame[args]
說明:執行宏定義macro-name。
4) append
說明:使用當前文件類型設置,將本地文件附加到遠程計算機中。大概格式是append local-file [remote-file] 其中local-file是說指定要添加的本地文件。remote-file是說指定要將local-file附加到遠程計算機文件,要是省了這個,則是使用本地文件名做遠程文件名。

⑸ java如何實現將FTP文件轉移到另一個FTP伺服器上

你有FTPClient就比較好辦,假如你的兩台FTP伺服器分別為fs1和fs2

在本地開發代碼思路如下:

  1. 通過FTPClient連接上fs1,然後下載(可以循環批量下載)到本地伺服器,保存到一個臨時目錄。

  2. 下載完成後,FTPClient斷開與fs1的連接,記得必須logout。

  3. 本地伺服器通過FileInputStream將剛下載到臨時目錄的文件讀進來,得到一個List<File>集合。

  4. 通過FTPClient連接上fs2,循環List<File>集合,將文件上傳至fs2的特定目錄,然後清空臨時目錄,上傳完畢後,斷開fs2的連接,同樣必須logout。

⑹ java如何實現兩台ftp伺服器之間的文件傳輸10

�0�2我知道apache有個commons net包,其中的FTPClient類可以實現客戶端和服務之間的文件傳輸,但是我如果使用這種方式的話,就得將一台伺服器上的文件傳到我本地,再將這個文件傳到另一台伺服器上,感覺這中間多了一步操作;我想請問大家如何能不通過本機,直接操作兩台伺服器,將文件從一台伺服器傳到另一台伺服器上,如果有人知道實現方式,希望不吝賜教,謝謝了!問題補充:<div class="quote_title"suziwen 寫道</div<div class="quote_div"把JAVA程序放在其中一台FTP服務 器A上,通過A伺服器上的JAVA登錄到另一台FTP伺服器,F代碼執行文 件的上傳,下載。 / /</div / /謝謝你們的回答,你們說的這種方式我明白。

⑺ java 將伺服器內的文件復制

你有FTPClient就比較好辦,假如你的兩台FTP伺服器分別為fs1和fs2
在本地開發代碼思路如下:
通過FTPClient連接上fs1,然後下載(可以循環批量下載)到本地伺服器,保存到一個臨時目錄。
下載完成後,FTPClient斷開與fs1的連接,記得必須logout。
本地伺服器通過FileInputStream將剛下載到臨時目錄的文件讀進來,得到一個List<File>集合。
通過FTPClient連接上fs2,循環List<File>集合,將文件上傳至fs2的特定目錄,然後清空臨時目錄,上傳完畢後,斷開fs2的連接,同樣必須logout。

⑻ 如何用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.");

⑼ java將一個伺服器下的文件復制到另一個伺服器的ftp上文件會少1kb

你有FTPClient就比較好辦,假如你的兩台FTP伺服器分別為fs1和fs2
在本地開發代碼思路如下:
通過FTPClient連接上fs1,然後下載(可以循環批量下載)到本地伺服器,保存到一個臨時目錄。
下載完成後,FTPClient斷開與fs1的連接,記得必須logout。
本地伺服器通過FileInputStream將剛下載到臨時目錄的文件讀進來,得到一個List<File>集合。
通過FTPClient連接上fs2,循環List<File>集合,將文件上傳至fs2的特定目錄,然後清空臨時目錄,上傳完畢後,斷開fs2的連接,同樣必須logout。

⑽ Java的ftp操作方法有哪幾種

FTP(File Transfer Protocol)是 Internet 上用來傳送文件的協議(文件傳輸協議)。它是為了我們能夠在 Internet 上互相傳送文件而制定的的文件傳送標准,規定了 Internet 上文件如何傳送。也就是說,通過 FTP 協議,我們就可以跟 Internet 上的 FTP 伺服器進行文件的上傳(Upload)或下載(Download)等動作。

和其他 Internet 應用一樣,FTP 也是依賴於客戶程序/伺服器關系的概念。在 Internet 上有一些網站,它們依照 FTP 協議提供服務,讓網友們進行文件的存取,這些網站就是 FTP 伺服器。網上的用戶要連上 FTP 伺服器,就要用到 FPT 的客戶端軟體,通常 Windows 都有「ftp」命令,這實際就是一個命令行的 FTP 客戶程序,另外常用的 FTP 客戶程序還有 CuteFTP、Ws_FTP、FTP Explorer等。

要連上 FTP 伺服器(即「登陸」),必須要有該 FTP 伺服器的帳號。如果是該伺服器主機的注冊客戶,你將會有一個 FTP 登陸帳號和密碼,就憑這個帳號密碼連上該伺服器。但 Internet 上有很大一部分 FTP 伺服器被稱為「匿名」(Anonymous)FTP 伺服器。這類伺服器的目的是向公眾提供文件拷貝服務,因此,不要求用戶事先在該伺服器進行登記注冊。

Anonymous(匿名文件傳輸)能夠使用戶與遠程主機建立連接並以匿名身份從遠程主機上拷貝文件,而不必是該遠程主機的注冊用戶。用戶使用特殊的用戶名「anonymous」和「guest」就可有限制地訪問遠程主機上公開的文件。現在許多系統要求用戶將Emai1地址作為口令,以便更好地對訪問進行跟綜。出於安全的目的,大部分匿名FTP主機一般只允許遠程用戶下載(download)文件,而不允許上載(upload)文件。也就是說,用戶只能從匿名FTP主機拷貝需要的文件而不能把文件拷貝到匿名FTP主機。另外,匿名FTP主機還採用了其他一些保護措施以保護自己的文件不至於被用戶修改和刪除,並防止計算機病毒的侵入。在具有圖形用戶界面的 WorldWild Web環境於1995年開始普及以前,匿名FTP一直是Internet上獲取信息資源的最主要方式,在Internet成千上萬的匿名PTP主機中存儲著無以計數的文件,這些文件包含了各種各樣的信息,數據和軟體。 人們只要知道特定信息資源的主機地址, 就可以用匿名FTP登錄獲取所需的信息資料。雖然目前使用WWW環境已取代匿名FTP成為最主要的信息查詢方式,但是匿名FTP仍是 Internet上傳輸分發軟體的一種基本方法

熱點內容
安卓怎麼像蘋果一樣滑動返回 發布:2024-10-09 08:20:46 瀏覽:756
gp資料庫行 發布:2024-10-09 08:10:37 瀏覽:415
會計公需課登錄密碼是什麼 發布:2024-10-09 08:08:20 瀏覽:798
wps怎麼怎麼加密碼忘了怎麼辦 發布:2024-10-09 07:54:30 瀏覽:989
埋堆堆怎樣更改緩存路徑 發布:2024-10-09 07:48:12 瀏覽:548
壹號本1s加存儲 發布:2024-10-09 07:43:51 瀏覽:544
少兒編程招生海報 發布:2024-10-09 07:43:51 瀏覽:424
電腦怎麼禁止雲伺服器 發布:2024-10-09 07:42:15 瀏覽:488
unturned怎麼不進伺服器聯機 發布:2024-10-09 07:24:17 瀏覽:393
javaoracle 發布:2024-10-09 07:23:32 瀏覽:560