TShopping

 找回密碼
 註冊
搜索
查看: 1874|回復: 0
打印 上一主題 下一主題

[教學] Android和FTP服務器交互下載文件(實測成功)

[複製鏈接]
跳轉到指定樓層
1#
發表於 2017-12-7 22:54:47 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
 
Push to Facebook
代碼
  1. private Boolean downloadAndSaveFile(String server, int portNumber,String user, String password, String filename, File localFile) throws IOException {
  2. FTPClient ftp = null;

  3. try {
  4.     ftp = new FTPClient();
  5.     ftp.connect(server, portNumber);
  6.     Log.d(LOG_TAG, "Connected. Reply: " + ftp.getReplyString());

  7.     ftp.login(user, password);
  8.     Log.d(LOG_TAG, "Logged in");
  9.     ftp.setFileType(FTP.BINARY_FILE_TYPE);
  10.     Log.d(LOG_TAG, "Downloading");
  11.     ftp.enterLocalPassiveMode();

  12.     OutputStream outputStream = null;
  13.     boolean success = false;
  14.     try {
  15.         outputStream = new BufferedOutputStream(new FileOutputStream(
  16.                 localFile));
  17.         success = ftp.retrieveFile(filename, outputStream);
  18.     } finally {
  19.         if (outputStream != null) {
  20.             outputStream.close();
  21.         }
  22.     }

  23.     return success;
  24. } finally {
  25.     if (ftp != null) {
  26.         ftp.logout();
  27.         ftp.disconnect();
  28.     }
  29. }
  30. }
複製代碼
如果是用暱名
user = "anonymous"

password=""


Android Studio build.gradle 加入
  1. dependencies {
  2.     compile fileTree(include: ['*.jar'], dir: 'libs')
  3.     testCompile 'junit:junit:4.12'
  4.     compile 'com.android.support:appcompat-v7:23.4.0'
  5.     compile 'commons-net:commons-net:3.6'
  6. }
複製代碼

下載時別忘了用 Thread

需要的Jar包下载地址:https://commons.apache.org/proper/commons-net/download_net.cgi
目前版本是:commons-net-3.6-bin.zip        


參考文章:https://stackoverflow.com/questi ... r-to-android-device


 

臉書網友討論
*滑块验证:
您需要登錄後才可以回帖 登錄 | 註冊 |

本版積分規則



Archiver|手機版|小黑屋|免責聲明|TShopping

GMT+8, 2024-4-23 15:13 , Processed in 0.096394 second(s), 22 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表