Java Commons Net 進行 FTP 檔案傳輸

利用 "Jakarta Commons Net" 外掛元件, 讓 Java 進行 FTP 動作.

 FTP 基本程式碼
<%@page import="org.apache.commons.net.ftp.FTPClient" %>
<%@page import="org.apache.commons.net.ftp.FTPReply" %>
<%@page contentType="text/html;charSet=Big5" %>

<%
String ftpServer = "***.***.***.***";
String ftpUsername = "***";
String ftpPassword = "***";

// 建立 FTP Client 物件
FTPClient ftp = new FTPClient();

try
{
// FTP 連線
ftp.connect( ftpServer );
out.println( "Connected to " + ftpServer + ". <br/>" );

// 顯示 FTP Server 回應資訊
out.println( ftp.getReplyString() + "<br/>" );

// 取得 FTP 回應碼
int reply = ftp.getReplyCode();

// FTP 連線失敗
if( !FTPReply.isPositiveCompletion(reply) )
{
ftp.disconnect();
out.println( ftpServer + " FTP server connect failure.<br/>" );
}

// FTP 連線成功
else
{
// FTP 登入
boolean ftpLogin = ftp.login( ftpUsername, ftpPassword );

// 登入失敗
if( ftpLogin == false )
{
out.println( ftpServer + " FTP server login failure.<br/>" );
}

// 登入成功
else
{
out.println( ftpServer + " FTP server login success.<br/>" );

// 登出
ftp.logout();
out.println( ftpServer + " FTP server logout.<br/>" );
}
}
}
catch( Exception e )
{
out.println( "錯誤: " + e.toString() + "<br/>" );
}
finally
{
// 若有連線, 則中斷之
if( ftp.isConnected() )
try
{
ftp.disconnect();
out.println( ftpServer + " FTP server is disconnected.<br/>" );
}
catch( Exception ioe )
{
// 不做任何事
}
}
%>

執行結果 :


 登入成功, 列出 FTP Server 檔案清單
// 更改 Remote 路徑
ftp.changeWorkingDirectory( "ftpServerPath" );

// 取得 FTP Server 檔案清單
String[] ftpFiles = ftp.listNames();

// 顯示 FTP Server 檔案清單
for( int i = 0; i < ftpFiles.length; i++ )
out.println( ftpFiles[i] + "<br/>" );

 登入成功, 下載 FTP Server 檔案
// 指定下載到本地端的檔案名稱
FileOutputStream fos = new FileOutputStream( "localFileName" );

// 指定要 FTP Server 檔案, 然後下載到本地端
ftp.retrieveFile( "ftpServerFileName", fos );
fos.close();

 登入成功, 上傳檔案到 FTP Server
// 指定要上傳到 FTP Server 的本地端檔案名稱
FileInputStream fis = new FileInputStream( "localFileName" );

// 指定上傳到 FTP Server 後的檔案名稱, 然後上傳
ftp.storeFile( "ftpServerFileName", fis );
fis.close();

以上, 希望對想透過 Java 做 FTP 工作的人, 有所幫助.
Related Posts Plugin for WordPress, Blogger...