Pages Navigation Menu

Coding is much easier than you think

Downloading file from FTP Server

Downloading file from FTP Server


FTPClient class supplies method to download files from FTP Servercomputer to the local/remote. We need another class FileOutputStream to handle the file during the transfer.

  • boolean retrieveFile(String remoteFile, OutputStream local) : This method fetches a specified file from the server and writes it to the specified OutputStream.
  • InputStream retrieveFileStream(String remoteFile) : This method returns an InputStream which is used to read the specified file from the server.

Here we are using retrieveFile(String remoteFile, OutputStream local) method. It throws FTPConnectionClosedException, CopyStreamException and IOException. This method is of boolean type and returns true if successfully downloaded otherwise returns false.

File : FtpFileDownload.java


package com.simplecode.com;

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

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

class FtpFileDownload {
	public static void main(String[] args) throws IOException {
		FTPClient ftpClient = new FTPClient();
		FileOutputStream fos = null;
		boolean result;
		try {
			// Connect to the localhost

			// login to ftp server
			result = ftpClient.login("", "");
			if (result == true) {
				System.out.println("Successfully logged in!");
			} else {
				System.out.println("Login Fail!");
			String fileName = "uploadfile.txt";
			fos = new FileOutputStream(fileName);

			// Download file from the ftp server
			result = ftpClient.retrieveFile(fileName, fos);

			if (result == true) {
				System.out.println("File downloaded successfully !");
			} else {
				System.out.println("File downloading failed !");
		} catch (FTPConnectionClosedException e) {
		} finally {
			try {
				if (fos != null) {
			} catch (FTPConnectionClosedException e) {

About Mohaideen Jamil

I'm a Full stack developer of IT exp in J2EE, AngularJs, MicroServices, Docker, Spring (Boot, MVC, Cloud), Bluemix, DevOps. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

%d bloggers like this: