TShopping
標題:
Android和FTP服務器交互下載文件(實測成功)
[打印本頁]
作者:
woff
時間:
2017-12-7 22:54
標題:
Android和FTP服務器交互下載文件(實測成功)
代碼
private Boolean downloadAndSaveFile(String server, int portNumber,String user, String password, String filename, File localFile) throws IOException {
FTPClient ftp = null;
try {
ftp = new FTPClient();
ftp.connect(server, portNumber);
Log.d(LOG_TAG, "Connected. Reply: " + ftp.getReplyString());
ftp.login(user, password);
Log.d(LOG_TAG, "Logged in");
ftp.setFileType(FTP.BINARY_FILE_TYPE);
Log.d(LOG_TAG, "Downloading");
ftp.enterLocalPassiveMode();
OutputStream outputStream = null;
boolean success = false;
try {
outputStream = new BufferedOutputStream(new FileOutputStream(
localFile));
success = ftp.retrieveFile(filename, outputStream);
} finally {
if (outputStream != null) {
outputStream.close();
}
}
return success;
} finally {
if (ftp != null) {
ftp.logout();
ftp.disconnect();
}
}
}
複製代碼
如果是用暱名
user =
"anonymous"
password=""
Android Studio build.gradle 加入
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'commons-net:commons-net:3.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
歡迎光臨 TShopping (http://www.tshopping.com.tw/)
Powered by Discuz! X3.2