Saturday, March 17, 2012

Android Connect to FTP server example


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;
}

25 comments:

  1. Excellent post. One missing feature. How to get the date/time from an FTP Server?

    ReplyDelete
  2. not working for me...........

    ReplyDelete
  3. Are you using apache libs, io and httpclient

    ReplyDelete
    Replies
    1. plz send complete code ...i am unable to integrate this code in my android project..

      Delete
  4. Working excellent....awesome post....

    ReplyDelete
  5. thank you very very much for this amazing and valuable tutorial.......

    ReplyDelete
  6. Hi, 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

    ReplyDelete
  7. Hi,

    Are you trying to upload data base files(Binary Files) e.g.: /data/data/dev.client.android/databases/clientDB.db

    Zana

    ReplyDelete
  8. Yes, first I'm making a copy of it on my SD card and then trying to upload.......

    ReplyDelete
  9. I can find every thing here. Very nice post.. Thank you so much.

    ReplyDelete
  10. hi!!
    this 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.

    ReplyDelete
  11. when i run the application it stops!! any help pls?? at the moment i am just connecting

    ReplyDelete
  12. hi
    i 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

    ReplyDelete
  13. Error encountered
    java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)

    ReplyDelete
  14. Will this use the REST feature? Which will resume the upload/download from the last file offset set.

    ReplyDelete
  15. I´m working with Android Studio but don't work connect() of FTPConnect().
    I 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

    ReplyDelete
    Replies
    1. In the AndroidManifest i have inserted
      ""

      Sorry

      Delete
    2. In the AndroidManifest i have inserted
      uses-permission android:name="android.permission.INTERNET"

      Delete
  16. Great post. Thanks. Just missing one little thing so the code would work for me. Add this to ftpConnect:

    try {
    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);

    ReplyDelete
  17. i need all the code help me please

    ReplyDelete
  18. I want complete source code. library not found..

    ReplyDelete
  19. HI!
    Library not found, Help me!

    ReplyDelete