Commons net實現 FTP上傳下載

來源:互聯網
上載者:User

最近項目中需要到Ftp檔案上傳,選擇了Commons net。Commons net包中的ftp工具類能夠協助我們輕鬆實現Ftp方式的檔案上傳/下載。其中最重要的一個類就是FTPClient類,這個提供了許多FTP操作相關的

方法,比如連結,登入,上傳,下載,和登出。

FTP 操作的過程一般為串連伺服器,登入,進行檔案上傳/下載,檔案(目錄)的添加刪除修改等操作。平常用的比較多的是檔案的上傳和下載。

下面是一些基本的上傳操作(將Commons net的jar包引入即可使用):

public class FtpUtil {public static void main(String[] args) {FTPClient ftpClient = new FTPClient();try {//串連指定伺服器,預設連接埠為21ftpClient.connect("127.0.0.1");System.out.println("connect to server");//擷取響應字串(FTP伺服器上可設定)String replyString = ftpClient.getReplyString();System.out.println("replyString: " + replyString);//擷取響應碼用於驗證是否串連成功int reply = ftpClient.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {System.out.println("");System.exit(1);}//設定連結編碼,windows主機UTF-8會亂碼,需要使用GBK或gb2312編碼ftpClient.setControlEncoding("GBK");//登入伺服器boolean login = ftpClient.login("luojing", "luojing");if (login) {System.out.println("登入成功!");} else {System.out.println("登入失敗!");}//擷取所有檔案和檔案夾的名字FTPFile[] files = ftpClient.listFiles();for(FTPFile file : files){if(file.isDirectory()){System.out.println(file.getName() + " 是檔案夾");}if(file.isFile()){System.out.println(file.getName() + " 是檔案");}}//產生InputStream用於上傳本地檔案InputStream in = new FileInputStream("e:\\1.txt");//上傳檔案ftpClient.storeFile("dest.txt",in);in.close();//登出登入boolean logout = ftpClient.logout();if (logout) {System.out.println("登出成功!");} else {System.out.println("登出失敗!");}} catch (Exception e) {e.printStackTrace();} finally {//關閉連結需要放在finally語句塊中if (ftpClient.isConnected()) {try {ftpClient.disconnect();} catch (IOException e) {e.printStackTrace();}}}}}

此外,FTPClient類中也提供了一些檔案/檔案夾操作的方法。通過commos net提供的方法,可以方便的實現斷點傳輸等功能。我還可以同個retrieveFileStream方法來擷取遠程伺服器中指定檔案的一個輸入資料流來供我們手動的進行讀操作,也可以使用appendFileStream方法來擷取要上傳到遠程伺服器中檔案對應的輸出資料流對象,然後我們就可以手動的從本地檔案中讀取資料然後寫入到遠程服務中,比如我們想知道上傳的進度。總的來說,Commons net提供的方法還是非常好使,非常方便的。一些其他的功能就需要在使用的時候去看API手冊了。 可能是環境影響,發現到了公司之後學習效率比在學校高了很多額,繼續加油。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.