Connect to FTP server example
This is the android coding example showing how to connect to FTP server and some basic file operations such as downloading, uploading, deleting, renaming file, and creating new directory.
You must import the following FTP client library, download it here:
import org.apache.commons.net.ftp.*;
Now, declare a public FTP client object.
public FTPClient mFTPClient = null;
Method to connect to FTP server:
public boolean ftpConnect(String host, String username, String password, int port) { try { mFTPClient = new FTPClient(); // connecting to the host mFTPClient.connect(host, port); // now check the reply code, if positive mean connection success if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) { // login using username & password boolean status = mFTPClient.login(username, password); /* Set File Transfer Mode * * To avoid corruption issue you must specified a correct * transfer mode, such as ASCII_FILE_TYPE, BINARY_FILE_TYPE, * EBCDIC_FILE_TYPE .etc. Here, I use BINARY_FILE_TYPE * for transferring text, image, and compressed files. */ mFTPClient.setFileType(FTP.BINARY_FILE_TYPE); mFTPClient.enterLocalPassiveMode(); return status; } } catch(Exception e) { Log.d(TAG, "Error: could not connect to host " + host ); } return false; }
Method to disconnect from FTP server:
public boolean ftpDisconnect() { try { mFTPClient.logout(); mFTPClient.disconnect(); return true; } catch (Exception e) { Log.d(TAG, "Error occurred while disconnecting from ftp server."); } return false; }
Method to get current working directory:
public String ftpGetCurrentWorkingDirectory() { try { String workingDir = mFTPClient.printWorkingDirectory(); return workingDir; } catch(Exception e) { Log.d(TAG, "Error: could not get current working directory."); } return null; }
Method to change working directory:
public boolean ftpChangeDirectory(String directory_path) { try { mFTPClient.changeWorkingDirectory(directory_path); } catch(Exception e) { Log.d(TAG, "Error: could not change directory to " + directory_path); } return false; }
Method to list all files in a directory:
public void ftpPrintFilesList(String dir_path) { try { FTPFile[] ftpFiles = mFTPClient.listFiles(dir_path); int length = ftpFiles.length; for (int i = 0; i < length; i++) { String name = ftpFiles[i].getName(); boolean isFile = ftpFiles[i].isFile(); if (isFile) { Log.i(TAG, "File : " + name); } else { Log.i(TAG, "Directory : " + name); } } } catch(Exception e) { e.printStackTrace(); } }
Method to create new directory:
public boolean ftpMakeDirectory(String new_dir_path) { try { boolean status = mFTPClient.makeDirectory(new_dir_path); return status; } catch(Exception e) { Log.d(TAG, "Error: could not create new directory named " + new_dir_path); } return false; }
Method to delete/remove a directory:
public boolean ftpRemoveDirectory(String dir_path) { try { boolean status = mFTPClient.removeDirectory(dir_path); return status; } catch(Exception e) { Log.d(TAG, "Error: could not remove directory named " + dir_path); } return false; }
Method to delete a file:
public boolean ftpRemoveFile(String filePath) { try { boolean status = mFTPClient.deleteFile(filePath); return status; } catch (Exception e) { e.printStackTrace(); } return false; }
Method to rename a file:
public boolean ftpRenameFile(String from, String to) { try { boolean status = mFTPClient.rename(from, to); return status; } catch (Exception e) { Log.d(TAG, "Could not rename file: " + from + " to: " + to); } return false; }
Method to download a file from FTP server:
/** * mFTPClient: FTP client connection object (see FTP connection example) * srcFilePath: path to the source file in FTP server * desFilePath: path to the destination file to be saved in sdcard */ public boolean ftpDownload(String srcFilePath, String desFilePath) { boolean status = false; try { FileOutputStream desFileStream = new FileOutputStream(desFilePath);; status = mFTPClient.retrieveFile(srcFilePath, desFileStream); desFileStream.close(); return status; } catch (Exception e) { Log.d(TAG, "download failed"); } return status; }
Method to upload a file to FTP server:
/** * mFTPClient: FTP client connection object (see FTP connection example) * srcFilePath: source file path in sdcard * desFileName: file name to be stored in FTP server * desDirectory: directory path where the file should be upload to */ public boolean ftpUpload(String srcFilePath, String desFileName, String desDirectory) { boolean status = false; try { FileInputStream srcFileStream = new FileInputStream(srcFilePath); // change working directory to the destination directory if (ftpChangeDirectory(desDirectory)) { status = mFTPClient.storeFile(desFileName, srcFileStream); } srcFileStream.close(); return status; } catch (Exception e) { Log.d(TAG, "upload failed"); } return status; }
Excellent post. One missing feature. How to get the date/time from an FTP Server?
ReplyDeletenot working for me...........
ReplyDeleteAre you using apache libs, io and httpclient
ReplyDeleteplz send complete code ...i am unable to integrate this code in my android project..
DeleteWorking excellent....awesome post....
ReplyDeletethank you very very much for this amazing and valuable tutorial.......
ReplyDeleteHi, its perfectly working for text files but i'm unable to properly upload sql files, just the tables are created but data is not there.....should I change the code for uploading my database files??? Please help........thank you
ReplyDeleteHi,
ReplyDeleteAre you trying to upload data base files(Binary Files) e.g.: /data/data/dev.client.android/databases/clientDB.db
Zana
Yes, first I'm making a copy of it on my SD card and then trying to upload.......
ReplyDeleteI can find every thing here. Very nice post.. Thank you so much.
ReplyDeleteyou’re welcome
ReplyDeletehi!!
ReplyDeletethis is a good post.i have a small error in ftpprintfilelist()method i want to send ftpfile[] to another activity to display it in a list view but no method worked. could you please help me out.i tried it out using intent method.my mail id is immortalscuffle@gmail.com.thank you.
when i run the application it stops!! any help pls?? at the moment i am just connecting
ReplyDeletehi
ReplyDeletei want to upload a database from /data/data/app name/database/.db to ftp server and to download when need,so send me your full android code
Error encountered
ReplyDeletejava.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)
Will this use the REST feature? Which will resume the upload/download from the last file offset set.
ReplyDeleteI´m working with Android Studio but don't work connect() of FTPConnect().
ReplyDeleteI have tested "connect(host,port)", "connect(host)", "connect(InetAddress.getByName(host),port)" and
"connect(InetAddress.getByName(host))", where host is the ip.
In the AndroidManifest i have inserted
""
Can anybody help me?¿
Thank you
In the AndroidManifest i have inserted
Delete""
Sorry
In the AndroidManifest i have inserted
Deleteuses-permission android:name="android.permission.INTERNET"
Great post. Thanks. Just missing one little thing so the code would work for me. Add this to ftpConnect:
ReplyDeletetry {
mFTPClient = new FTPClient();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// connecting to the host
mFTPClient.connect(host, port);
i need all the code help me please
ReplyDeleteabout what?
DeleteI want complete source code. library not found..
ReplyDeleteHI!
ReplyDeleteLibrary not found, Help me!
Exellent post !!!!!
ReplyDelete