當前位置:首頁 » 文件管理 » java連接ftp伺服器

java連接ftp伺服器

發布時間: 2022-09-05 18:31:05

java如何測試連接ftp是否通

java測試連接ftp是否連通可以使用判斷是否有異常來決定,實例如下:

/**
*connectServer
*連接ftp伺服器
*@throwsjava.io.IOException
*@parampath文件夾,空代表根目錄
*@parampassword密碼
*@paramuser登陸用戶
*@paramserver伺服器地址
*/
publicvoidconnectServer(Stringserver,Stringuser,Stringpassword,Stringpath)
throwsIOException
{
//server:FTP伺服器的IP地址;user:登錄FTP伺服器的用戶名
//password:登錄FTP伺服器的用戶名的口令;path:FTP伺服器上的路徑
ftpClient=newFtpClient();
ftpClient.openServer(server);
ftpClient.login(user,password);
//path是ftp服務下主目錄的子目錄
if(path.length()!=0)ftpClient.cd(path);
//用2進制上傳、下載
ftpClient.binary();
}

/**
*upload
*上傳文件
*@throwsjava.lang.Exception
*@return-1文件不存在
*-2文件內容為空
*>0成功上傳,返迴文件的大小
*@paramnewname上傳後的新文件名
*@paramfilename上傳的文件
*/
publiclongupload(Stringfilename,Stringnewname)throwsException
{
longresult=0;
TelnetOutputStreamos=null;
FileInputStreamis=null;
try{
java.io.Filefile_in=newjava.io.File(filename);
if(!file_in.exists())return-1;
if(file_in.length()==0)return-2;
os=ftpClient.put(newname);
result=file_in.length();
is=newFileInputStream(file_in);
byte[]bytes=newbyte[1024];
intc;
while((c=is.read(bytes))!=-1){
os.write(bytes,0,c);
}
}finally{
if(is!=null){
is.close();
}
if(os!=null){
os.close();
}
}
returnresult;
}
/**
*upload
*@throwsjava.lang.Exception
*@return
*@paramfilename
*/
publiclongupload(Stringfilename)
throwsException
{
Stringnewname="";
if(filename.indexOf("/")>-1)
{
newname=filename.substring(filename.lastIndexOf("/")+1);
}else
{
newname=filename;
}
returnupload(filename,newname);
}

/**
*download
*從ftp下載文件到本地
*@throwsjava.lang.Exception
*@return
*@paramnewfilename本地生成的文件名
*@paramfilename伺服器上的文件名
*/
publiclongdownload(Stringfilename,Stringnewfilename)
throwsException
{
longresult=0;
TelnetInputStreamis=null;
FileOutputStreamos=null;
try
{
is=ftpClient.get(filename);
java.io.Fileoutfile=newjava.io.File(newfilename);
os=newFileOutputStream(outfile);
byte[]bytes=newbyte[1024];
intc;
while((c=is.read(bytes))!=-1){
os.write(bytes,0,c);
result=result+c;
}
}catch(IOExceptione)
{
e.printStackTrace();
}
finally{
if(is!=null){
is.close();
}
if(os!=null){
os.close();
}
}
returnresult;
}
/**
*取得某個目錄下的所有文件列表
*
*/
publicListgetFileList(Stringpath)
{
Listlist=newArrayList();
try
{
DataInputStreamdis=newDataInputStream(ftpClient.nameList(path));
Stringfilename="";
while((filename=dis.readLine())!=null)
{
list.add(filename);
}

}catch(Exceptione)
{
e.printStackTrace();
}
returnlist;
}

/**
*closeServer
*斷開與ftp伺服器的鏈接
*@throwsjava.io.IOException
*/
publicvoidcloseServer()
throwsIOException
{
try
{
if(ftpClient!=null)
{
ftpClient.closeServer();
}
}catch(IOExceptione){
e.printStackTrace();
}
}

publicstaticvoidmain(String[]args)throwsException
{
FtpUtilftp=newFtpUtil();
try{
//連接ftp伺服器
ftp.connectServer("10.163.7.15","cxl","1","info2");
/**上傳文件到info2文件夾下*/
System.out.println("filesize:"+ftp.upload("f:/download/Install.exe")+"位元組");
/**取得info2文件夾下的所有文件列表,並下載到E盤下*/
Listlist=ftp.getFileList(".");
for(inti=0;i<list.size();i++)
{
Stringfilename=(String)list.get(i);
System.out.println(filename);
ftp.download(filename,"E:/"+filename);
}
}catch(Exceptione){
///
}finally
{
ftp.closeServer();
}
}
}

② Java怎麼均衡訪問多台ftp伺服器

多次需要把文件上傳到單獨的伺服器,而程序是在單獨的伺服器上部署的,在進行文件操作的時候就需要跨伺服器進行操作包括:文件上傳、文件下載、文件刪除等。跨伺服器文件操作一般是需要FTP協議和SFTP協議兩種,現在就通過Java實現FTP協議的文件上傳。要實現FTP操作文件需要引入jar包: commons-net-1.4.1.jar
參考資料來源:網路貼吧

③ java中怎麼實現ftp伺服器

我知道apache有個commons net包,其中的FTPClient類可以實現客戶端和服務之間的文件傳輸,但是我如果使用這種方式的話,就得將一台伺服器上的文件傳到我本地,再將這個文件傳到另一台伺服器上,感覺這中間多了一步操作;

④ 如何用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);
}

⑤ 為什麼java用ftp的方式連接不到伺服器

ftp伺服器沒有按照協議返回響應代碼吧

加這行打開調試信息看看咯
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

應該有類似的顯示。其中220表示伺服器成功響應。
Connected to 10.17.37.21.
220 v890 FTP server ready.

如果確實login()成功而伺服器未能按照規范響應代碼,把後面檢測是否成功的代碼注釋掉就可以。

⑥ java程序可以成功連接Ftp伺服器,但無法上傳文件,怎麼回事,報錯如下,(已設置連接超時時間200s)

我感覺有倆問題,1、連接地址和帳號不是一回事,你最好不要用域名做連接地址,可以用IP地址;2、你是在不行通過空間服務商進入線上後台,如果還不行就聯系空間商,可能是他們的問題.果是VPS的話好像要開通ftp某些許可權才可以,你只是開通了帳號,能連接,並沒有給ftp上傳下載的許可權,這個我在空間商裡面看過教程的,在這沒網路不讓發連接,你可以在網路搜一下試試,希望能幫助你。

⑦ java 連接 ftp 需要的 知識

這個網上有很多例子程序的,去開源中國看看吧。 http://www.oschina.net/code/search?q=java+ftp

⑧ JAVA編寫FTP連接報錯java.net.ConnectException: Connection refused: connect FTP

你用的FTPClient引入不對吧,我們項目上都是用的

import org.apache.commons.net.ftp.FTPClient;

import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

下面是我們項目上用到的FTP的實現代碼(FTP需要先連接,再登錄,之後就是校驗登錄是否成功),具體代碼如下:

/**
*獲取FTPClient對象
*
*@paramftpHostFTP主機伺服器
*@paramftpPasswordFTP登錄密碼
*@paramftpUserNameFTP登錄用戶名
*@paramftpPortFTP埠默認為21
*@returnFTPClient
*@throwsException
*/
(StringftpHost,StringftpUserName,
StringftpPassword,intftpPort)throwsException{
try{
FTPClientftpClient=newFTPClient();
ftpClient.connect(ftpHost,ftpPort);//連接FTP伺服器
ftpClient.login(ftpUserName,ftpPassword);//登陸FTP伺服器
if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
logger.error("未連接到FTP,用戶名或密碼錯誤!");
ftpClient.disconnect();
returnnull;
}else{
logger.info("FTP連接成功!");
returnftpClient;
}
}catch(){
logger.error("FTP的IP地址可能錯誤,請正確配置!");
throwsocketException;
}catch(IOExceptionioException){
logger.error("FTP的埠錯誤,請正確配置!");
throwioException;
}
}

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

熱點內容
網站編程培訓 發布:2024-10-12 06:09:22 瀏覽:900
怎麼看自己的電腦配置玩永劫無間 發布:2024-10-12 05:56:41 瀏覽:466
linuxzip文件解壓命令 發布:2024-10-12 05:56:03 瀏覽:942
java怎麼處理高並發 發布:2024-10-12 05:55:25 瀏覽:764
五子棋java源碼 發布:2024-10-12 05:37:13 瀏覽:175
pythonopenstack怎麼配置 發布:2024-10-12 05:16:07 瀏覽:929
安卓如何編輯動畫 發布:2024-10-12 05:14:25 瀏覽:348
視頻電腦配置高怎麼玩游戲 發布:2024-10-12 04:35:56 瀏覽:731
sql復合查詢 發布:2024-10-12 04:14:23 瀏覽:715
把文檔加密 發布:2024-10-12 04:13:52 瀏覽:850