Open In App

How to Download Files From FTP Server in Java?

Last Updated : 20 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to download files from an FTP server in Java. After successfully connecting to the FTP server, the function below in the FtpConnector class will return an FTPClient object.

FTPClient: All the functionality required to save and retrieve files from an FTP server is included in FTPClient. This class provides a comfortable higher-level interface while handling all the low-level specifics of interfacing with an FTP server. Determine the transferable file type. Either FTP.ASCII FILE TYPE or FTP.BINARY FILE TYPE should be used here. Mostly, the default file type is set to ASCII. 

Turn on the PASSIVE LOCAL DATA CONNECTION MODE for the current data connection mode. Just use this technique to send data between the client and server. This technique causes a PASV (or EPSV) instruction to be sent to the server before each data connection is established, instructing it to open a data port to which the client will connect in order to carry out data transfers. The FTPClient will remain in the PASSIVE LOCAL DATA CONNECTION MODE until another method, such as enterLocalActiveMode, is called to alter the mode. 

Implementation

File: FtpConnector.java

Java




import java.io.*;
import java.io.IOException;
import java.net.UnknownHostException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
  
public class FtpConnector {
  
    Logger logger
        = LoggerFactory.getLogger(FtpConnector.class);
  
    public FTPClient connect() throws IOException
    {
        // Create an instance of FTPClient
        FTPClient ftpClient = new FTPClient();
        try {
            // establish a connection with specific host and
            // port.
            ftpClient.connect("localhost", 21);
  
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                logger.info(
                    "Operation failed. Server reply code: "
                    + replyCode);
                ftpClient.disconnect();
            }
  
            // login to ftp server with username and
            // password.
            boolean success
                = ftpClient.login("testuser", "123");
            if (!success) {
                ftpClient.disconnect();
            }
            // assign file type according to the server.
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
  
            // change specific directory of ftp server from
            // you want to download files.
            boolean changedRemoteDir
                = ftpClient.changeWorkingDirectory(
                    "/home/testuser/directory");
            if (!changedRemoteDir) {
                logger.info("Remote directory not found.");
            }
        }
        catch (UnknownHostException E) {
            logger.info("No such ftp server");
        }
        catch (IOException e) {
            logger.info(e.getMessage());
        }
        return ftpClient;
    }
}


The FtpDownloader class contains the main method that’s responsible for downloading files from the FTP server.

File: FtpDownloader.java

Java




import java.io.*;
import java.nio.file.Files;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
  
public class FtpDownloader {
    static Logger logger
        = LoggerFactory.getLogger(FtpDownloader.class);
  
    public static void main(String[] args)
        throws IOException
    {
  
        // create a instance of FtpConnector
        FtpConnector ftpConnector = new FtpConnector();
  
        // get ftp client object.
        FTPClient ftpClient = ftpConnector.connect();
  
        // list all the files which will be downloaded.
        FTPFile[] ftpFiles = ftpClient.listFiles();
  
        // set downloading dir where all the files will be
        // stored on local directory.
        String downloading_dir
            = "/Downloads/FtpDownloaded/";
  
        for (FTPFile file : ftpFiles) {
            File fileObj = new File(downloading_dir
                                    + file.getName());
            Files.createFile(fileObj.toPath());
            try (OutputStream outputStream
                 = new BufferedOutputStream(
                     new FileOutputStream(fileObj))) {
                
                // ftpclient.retrieveFile will get the file
                // from Ftp server and write it in
                // outputStream.
                boolean isFileRetrieve
                    = ftpClient.retrieveFile(file.getName(),
                                             outputStream);
                logger.info("{} file is downloaded : {}",
                            file.getName(), isFileRetrieve);
            }
        }
    }
}


Output:

Files downloaded successfully from ftp server.

Files downloaded successfully from ftp server.

Local folder where files are stored.

Local folder where files are stored.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads