Download file from FTP Server Using Java


How to download file from FTP(File Transfer Protocol)?

Reference : here

You must download commons-net-3.3.jar. This is source of FTP library.

 

package file.ftp.download;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.Iterator;

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

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

 

public class DownloadFileFTP {

public static void main(String[] args) {

FTPClient ftpClient = new FTPClient();

FileOutputStream fos = null;

FileInputStream fis = null;

String hostname = “[Path for access FTP Server]”;

int port = 21; //port default

String user = “[User for login FTP server]”;

String pass = “[Password for login FTP server]”;

//Get File From FTP 

try {

ftpClient.connect(hostname, port);

boolean login = ftpClient.login(user, pass);

if(login){

System.out.println(“Connection established…”);

//Set File location for download 

FTPFile[] files = ftpClient.listFiles(“Current/”); //directory from FTP

for (FTPFile file : files) {

if (file.isFile()) {

System.out.println(file.getName());

//We will save it in our PC

fos = new FileOutputStream(“D:\\ftp\\process\\” + file.getName());

boolean download = ftpClient.retrieveFile(“Current/” + file.getName(),fos);

if (download) {

System.out.println(“File downloaded successfully !”);

} else {

System.out.println(“Error in downloading file !”);

}

}

}

}

} catch (Exception e) {

e.printStackTrace();

System.out.println(“Error: ” + e.getMessage());

} finally{

try {

if (ftpClient.isConnected()) {

boolean logout = ftpClient.logout();

ftpClient.disconnect();

if (logout) {

System.out.println(“Connection close…”);

} else {

System.out.println(“Connection fail…”);

}

}

} catch (IOException ex) {

ex.printStackTrace();

}

}

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s