Tuesday, December 10, 2013

FTP Multiple files download in android


Here is the full source code,To Connect,authenticate and get files from FTP Server.Below requirements are needed for successfully connections.

Requirements:

  1. FTP server URL
  2. Username and Password

Steps:

  1. First of all we need to connect the FTP server using its URL.
  2. after successfully connection you need to authenticate and access your files.
  3. After login you can get all files and directories list.
  4. Now the main part is to get files one by one and save in your local device.

Here is the full source code for this operation, check below source code carefully.

import java.io.File;
import java.io.FileOutputStream;
import java.net.InetAddress;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class Downloads implements Runnable{

String TAG = "Downloads";
int fl = 0;
Context c ;
public Downloads(Context context) {
try {
final FTPClient ftp = new FTPClient();
final File dir = new File(Environment.getExternalStorageDirectory()
+ "/Android_guide");

if (!dir.exists()) {
dir.mkdir();
}
FTPFile[] filesList = null;
                        //FTP Server connection
ftp.connect(InetAddress.getByName("FTP file URL"));
//FTP username and password authentication
                        ftp.login("Username", "Password");
ftp.enterLocalPassiveMode();
//To change directory of FTP Server 
                        // ftp.changeWorkingDirectory("/");
filesList = ftp.listFiles("");
ftp.setFileType(FTP.BINARY_FILE_TYPE);
Log.v("Coneection and login", "Successfully");
// -----------------------------
while (fl < filesList.length) {
try {
Log.v("File name", filesList[fl].getName());
boolean status = false;
try {
                          FileOutputStream desFileStream = new FileOutputStream(
dir+ dir.separator+ filesList[fl].getName());

status = ftp.retrieveFile(filesList[fl].getName(),desFileStream);
Log.v("status", "" + status);
desFileStream.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
              e.printStackTrace();
}
fl++;
}
ftp.logout();
ftp.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}

  • Thats it. But dont forget to give permission for WRITE EXTERNAL STORAGE
Add following permission in android menifest file.

android.permission.WRITE_EXTERNAL_STORAGE


To configure your project with FTP, You need to download following libraries.

  1. org.apache.commons.net_2.0.0.v200905272248.jar
  2. commons-net-1.4.1.jar

Download above libraries Here

1 comment: