Blog Archive

Apache commons FTPClient Java example - Download files from server

File Transfer Protocol (FTP) is a standard network protocol used to transfer files from one host to another host over a TCP-based network, such as the Internet. It is often used to upload web pages and other documents from a private development machine to a public web-hosting server. FTP is built on a client-server architecture and uses separate control and data connections between the client and the server.

FTPClient encapsulates all the functionality necessary to store and retrieve files from an FTP server. This class takes care of all low level details of interacting with an FTP server and provides a convenient higher level interface.

You must first connect to the server with connect before doing anything, and finally disconnect after you're completely finished interacting with the server. Then you need to check the FTP reply code to see if the connection was successful. Here is an example that downloads files from a specific directory on the FTP server and then delete them.

Please download the jar file from the Apache commons Website given below and add to your project Java build path.
http://commons.apache.org/net/download_net.cgi

package com.as400samplecode;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Properties;

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

public class GetMyFiles {

    static Properties props;

    public static void main(String[] args) {

        GetMyFiles getMyFiles = new GetMyFiles();
        if (args.length < 1)
        {
            System.err.println("Usage: java " + getMyFiles.getClass().getName()+
            " Properties_file");
            System.exit(1);
        }

        String propertiesFile = args[0].trim();
        getMyFiles.startFTP(propertiesFile);

    }

    public boolean startFTP(String propertiesFile){

        props = new Properties();

        try {

            props.load(new FileInputStream("properties/" + propertiesFile));

            String serverAddress = props.getProperty("serverAddress").trim();
            String userId = props.getProperty("userId").trim();
            String password = props.getProperty("password").trim();
            String remoteDirectory = props.getProperty("remoteDirectory").trim();
            String localDirectory = props.getProperty("localDirectory").trim();
           
            //new ftp client
            FTPClient ftp = new FTPClient();
            //try to connect
            ftp.connect(serverAddress);
            //login to server
            if(!ftp.login(userId, password))
            {
                ftp.logout();
                return false;
            }
            int reply = ftp.getReplyCode();
            //FTPReply stores a set of constants for FTP reply codes. 
            if (!FTPReply.isPositiveCompletion(reply))
            {
                ftp.disconnect();
                return false;
            }

            //enter passive mode
            ftp.enterLocalPassiveMode();
            //get system name
            System.out.println("Remote system is " + ftp.getSystemType());
            //change current directory
            ftp.changeWorkingDirectory(remoteDirectory);
            System.out.println("Current directory is " + ftp.printWorkingDirectory());
             
            //get list of filenames
            FTPFile[] ftpFiles = ftp.listFiles();  
           
            if (ftpFiles != null && ftpFiles.length > 0) {
                //loop thru files
                for (FTPFile file : ftpFiles) {
                    if (!file.isFile()) {
                        continue;
                    }
                    System.out.println("File is " + file.getName());
                   
                   
                    //get output stream
                    OutputStream output;
                    output = new FileOutputStream(localDirectory + "/" + file.getName());
                    //get the file from the remote system
                    ftp.retrieveFile(file.getName(), output);
                    //close output stream
                    output.close();
                   
                    //delete the file
                    ftp.deleteFile(file.getName());
                   
                }
            }
           
            ftp.logout();
            ftp.disconnect();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            return false;
        }
        return true;
    }

}

Source for the properties file ftp.properties

#Properties File FTP to server

serverAddress=ftp.someDomain.com
userId=yourUserId   
password=yourPassword
remoteDirectory=/remote/MyFolder
localDirectory=/local/MyFolder

Recommended Reading


5 comments :

  1. With that code I had problem when files were bigger than 1024 bytes. I solved the problem incresing the buffer size with FTPClient.setBufferSize(1024 * 1024);

    ReplyDelete
    Replies
    1. The problem was that the application hang a lot time. Thanks

      Delete
  2. your example is very good. Similary can u update with copy complete directory to local machine it would be to nice.

    ReplyDelete
  3. great example!!! I have one thing to add here: if you are trying to retrieve a binary file you have to set the file type otherwise the retrieved file will be corrupted: ftp.setFileType(FTP.BINARY_FILE_TYPE);

    ReplyDelete
  4. i've a problem when i want to delete a list of files. The remote ftp server is the natuive ftp server of Windows.
    Sometime the script could not delete a file (error code 550), sometimes it can.
    I've you got an idea to resolve my issue?
    Thnxs

    ReplyDelete