在JAVA程式中,經常需要和FTP打交道,比如向FTP伺服器上傳檔案、下載檔案,本文簡單介紹如何利用jakarta commons中的FTPClient(在commons-net包中)實現上傳下載檔案。
所用到的jar包有:
commons-net-1.4.1.jar
jakarta-oro.jar
一、上傳檔案 查看源碼 列印 ?
| 03 |
* Description: 向FTP伺服器上傳檔案 |
| 05 |
* @param url FTP伺服器hostname |
| 06 |
* @param port FTP伺服器連接埠 |
| 07 |
* @param username FTP登入帳號 |
| 08 |
* @param password FTP登入密碼 |
| 09 |
* @param path FTP伺服器儲存目錄 |
| 10 |
* @param filename 上傳到FTP伺服器上的檔案名稱 |
| 12 |
* @return 成功返回true,否則返回false |
| 14 |
public static boolean uploadFile( |
| 15 |
String url,//FTP伺服器hostname |
| 17 |
String username, // FTP登入帳號 |
| 18 |
String password, //FTP登入密碼 |
| 19 |
String path, //FTP伺服器儲存目錄 |
| 20 |
String filename, //上傳到FTP伺服器上的檔案名稱 |
| 21 |
InputStream input // 輸入資料流 |
| 23 |
boolean success = false; |
| 24 |
FTPClient ftp = new FTPClient(); |
| 27 |
ftp.connect(url, port);//串連FTP伺服器 |
| 28 |
//如果採用預設連接埠,可以使用ftp.connect(url)的方式直接連接FTP伺服器 |
| 29 |
ftp.login(username, password);//登入 |
| 30 |
reply = ftp.getReplyCode(); |
| 31 |
if (!FTPReply.isPositiveCompletion(reply)) { |
| 35 |
ftp.changeWorkingDirectory(path); |
| 36 |
ftp.storeFile(filename, input); |
| 41 |
} catch (IOException e) { |
| 44 |
if (ftp.isConnected()) { |
| 47 |
} catch (IOException ioe) { |
以下是檔案上傳的測試案例: 查看源碼 列印 ?
| 05 |
public void testUpLoadFromDisk(){ |
| 07 |
FileInputStream in=new FileInputStream(new File("D:/test.txt")); |
| 08 |
boolean flag = uploadFile("127.0.0.1", 21, "administrator", "zyuc2011", "test", "test.txt", in); |
| 09 |
System.out.println(flag); |
| 10 |
} catch (FileNotFoundException e) { |
查看源碼 列印 ?
| 02 |
* 在FTP伺服器上產生一個檔案,並將一個字串寫入到該檔案中 |
| 05 |
public void testUpLoadFromString(){ |
| 07 |
String str = "這是要寫入的字串。"; |
| 08 |
InputStream input = new ByteArrayInputStream(str.getBytes("utf-8")); |
| 09 |
boolean flag = uploadFile("127.0.0.1", 21, "administrator", "zyuc2011", "test", "test.txt", input); |
| 10 |
System.out.println(flag); |
| 11 |
} catch (UnsupportedEncodingException e) { |
二、檔案下載 查看源碼 列印 ?
| 03 |
* Description: 從FTP伺服器下載檔案 |