JAVA中使用FTPClient實現檔案上傳下載__JAVA

來源:互聯網
上載者:User

在JAVA程式中,經常需要和FTP打交道,比如向FTP伺服器上傳檔案、下載檔案,本文簡單介紹如何利用jakarta commons中的FTPClient(在commons-net包中)實現上傳下載檔案。

所用到的jar包有: 

commons-net-1.4.1.jar 

jakarta-oro.jar 

一、上傳檔案 查看源碼 列印 ?

01 檔案上傳原始碼 
02 /** 
03 * Description: 向FTP伺服器上傳檔案 
04 * @Version1.0 
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伺服器上的檔案名稱 
11 * @param input 輸入資料流 
12 * @return 成功返回true,否則返回false 
13 */ 
14 public static boolean uploadFile( 
15 String url,//FTP伺服器hostname 
16 int port,//FTP伺服器連接埠 
17 String username, // FTP登入帳號 
18 String password, //FTP登入密碼 
19 String path, //FTP伺服器儲存目錄 
20 String filename, //上傳到FTP伺服器上的檔案名稱 
21 InputStream input // 輸入資料流 
22 ) { 
23 boolean success = false; 
24 FTPClient ftp = new FTPClient(); 
25 try { 
26 int reply; 
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)) { 
32 ftp.disconnect(); 
33 return success; 
34 } 
35 ftp.changeWorkingDirectory(path); 
36 ftp.storeFile(filename, input); 
37
38 input.close(); 
39 ftp.logout(); 
40 success = true; 
41 } catch (IOException e) { 
42 e.printStackTrace(); 
43 } finally { 
44 if (ftp.isConnected()) { 
45 try { 
46 ftp.disconnect(); 
47 } catch (IOException ioe) { 
48 } 
49 } 
50 } 
51 return success; 
52 }

以下是檔案上傳的測試案例: 查看源碼 列印 ?

01 /** 
02 * 將本地檔案上傳到FTP伺服器上 
03 * 
04 */ 
05 public void testUpLoadFromDisk(){ 
06 try { 
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) { 
11 e.printStackTrace(); 
12 } 
13 }
查看源碼 列印 ?
01 /** 
02 * 在FTP伺服器上產生一個檔案,並將一個字串寫入到該檔案中 
03 * 
04 */ 
05 public void testUpLoadFromString(){ 
06 try { 
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) { 
12 e.printStackTrace(); 
13 } 
14 }

二、檔案下載 查看源碼 列印 ?

01 檔案下載原始碼 
02 /** 
03 * Description: 從FTP伺服器下載檔案 
04

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.