Java FTP Download Example – Apache Commons Net

Filed Under: Java

Today we will look into Java FTP download file example using Apache Commons Net API. Few days back I wrote a post on how to FTP Upload File using Apache Commons Net API. Here we will learn how to use apache commons Net API to download file from FTP server.

Java FTP Download

java ftp download file example using apache commons net api


package com.journaldev.files;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

public class FTPDownloader {

    FTPClient ftp = null;

    public FTPDownloader(String host, String user, String pwd) throws Exception {
        ftp = new FTPClient();
        ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
        int reply;
        ftp.connect(host);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            throw new Exception("Exception in connecting to FTP Server");
        }
        ftp.login(user, pwd);
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
    }

    public void downloadFile(String remoteFilePath, String localFilePath) {
        try (FileOutputStream fos = new FileOutputStream(localFilePath)) {
            this.ftp.retrieveFile(remoteFilePath, fos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void disconnect() {
        if (this.ftp.isConnected()) {
            try {
                this.ftp.logout();
                this.ftp.disconnect();
            } catch (IOException f) {
                // do nothing as file is already downloaded from FTP server
            }
        }
    }

    public static void main(String[] args) {
        try {
            FTPDownloader ftpDownloader =
                new FTPDownloader("ftp_server.journaldev.com", "ftp_user@journaldev.com", "ftpPassword");
            ftpDownloader.downloadFile("sitemap.xml", "/Users/pankaj/tmp/sitemap.xml");
            System.out.println("FTP File downloaded successfully");
            ftpDownloader.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In above program constructor, we are creating FTP connection and then using downloadFile() method to download the file located on FTP server to local system. FTPClient retrieveFile() method is used to download file from FTP server.

Note that the remote file path should be relative to the FTP user home directory.

Here is the output of the above FTP download file example program.


220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
220-You are user number 1 of 50 allowed.
220-Local time is now 01:39. Server port: 21.
220-This is a private system - No anonymous login
220 You will be disconnected after 15 minutes of inactivity.
USER ftp_user@journaldev.com
331 User ftp_user@journaldev.com OK. Password required
PASS ftpPassword
230 OK. Current restricted directory is /
TYPE I
200 TYPE is now 8-bit binary
PASV
227 Entering Passive Mode (50,116,65,161,255,56)
RETR sitemap.xml
150-Accepted data connection
150 1427.4 kbytes to download
226-File successfully transferred
226 1.900 seconds (measured here), 0.73 Mbytes per second
FTP File downloaded successfully
QUIT
221-Goodbye. You uploaded 0 and downloaded 1428 kbytes.
221 Logout.

That’s all for FTP download file example using Apache commons Net API.

Comments

  1. sy says:

    Thanks!
    Your code is very helpful!

  2. mahantesh says:

    How can we download multiple files from ftp server

  3. putin says:

    FTPClient#retrieveFile() does NOT close the given OutputStream.

  4. vikram says:

    Start
    220-Microsoft FTP Service
    220 ************* it Dev FTP **********
    USER 5024757
    331 Password required for 502475728.
    PASS pass
    230-************* it Dev FTP ************
    230 User logged in.
    TYPE I
    200 Type set to I.
    PASV
    227 Entering Passive Mode (3,175,193,32,221,72).
    STOR /502475728
    550 Access is denied.
    QUIT
    221 Goodbye.
    Done
    The Above issues am facing..please could u help me on this.
    thanks in advance

  5. Shant Prakash Rai says:

    Hi ,
    I have requirement like while downloading file i need inputstream .
    So could you sugest me any method which return type is inputstream from ftpclient.?

  6. Ankit says:

    Hi Pankaj,
    Great tutorial, actually i am using the above function retreiveFile(),But in output shows:
    550 /3XXX131XXX9.xml.gz: No such file or directory.
    always.It just make copy of this file in my local with 0bytes.Please help me.

  7. adhir mukati says:

    HI Pankaj ,

    When i try to download file its giving 550 Failed to open file. Can you tell me how can we download file from the filezilla .I think there is problem with port or firewall .

    Thanks in advance

  8. Hi, I need your assistance in FTP

    1. how to get File owner from above program. Is it possible to get file owner from FTP server.

    2. Other than apache commons api’s, please suggest other FTP api’s . Need to explore on it.

  9. Himanshu says:

    How can i download multiple files … ?

  10. Himanshu says:

    Thank you very much Pankaj sir,

    Your downloading code working fine

  11. Rakesh Konda says:

    Hi Pankaj,
    Could you please explain more about ftp.enterLocalPassiveMode(), is this required? I am trying to download a file from SFTP server to a server on Amazon Cloud.. This download happens once in a week.. What mode is suggested?

    Also, would this work for Secure connection i.e., SFTP??

    Please let me know

    Thanks
    -Rakesh

  12. Venkateswarlu Padigala says:

    Hi Pankaj,

    While trying to retrieve the file from FTP, we are testing the negative scenario and passing the wrong file name, but did not get any exception like file not found exception. From the api also we observed that public boolean retrieveFile(String remote, OutputStream local) throws IOException, doesnot throw the FileNotFound exception. How to deal with this scenario?

    If possible please reply to my mail id pvenkatiitm@gmail.com
    Regards,
    Venkat

  13. Jitendra says:

    Hi,
    Connection is not being established using this code. I tried
    try{
    ftp.connect(ip);
    }catch(Exception e){
    System.out.println(“Conncetion Exception: “+e);
    }

    Here ip is an IP Address.
    This is what I am getting
    Conncetion Exception: java.net.ConnectException: Connection refused: connect

    1. Pankaj says:

      Are you able to connect with IP and user/password through some FTP Client like FileZilla? If that works, this should work too.

  14. Miguel says:

    Very usefull!
    What changes would be required in this code in order to use FTPSClient?

  15. Bruno says:

    Thanks!
    Your code save me.
    This line: “ftp.enterLocalPassiveMode();” resolved my problem with return listaNames() and return listFiles() to null.

    1. Pankaj says:

      you are welcome Bruno.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages