FTP Server : Download file

This tutorial contains description of file downloading from the FTP server using java.

FTP Server : Download file

FTP Server : Download file

This tutorial contains description of file downloading from the FTP server using java.

Download File : FTPClient class supplies method to download  files from FTP Server computer 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.

Example :


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

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

class FtpDownloadFile {
	public static void main(String[] args) throws IOException {
		FTPClient client = new FTPClient();
		FileOutputStream fos = null;
		boolean result;
		try {
			client.connect("localhost");
			result = client.login("admin", "admin");

			if (result == true) {
				System.out.println("Successfully logged in!");
			} else {
				System.out.println("Login Fail!");
				return;
			}
		
			String fileName = "test.txt";
			fos = new FileOutputStream(fileName);

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

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

Output :

Successfully logged in!
File is downloaded successfully!