Pages Navigation Menu

Coding is much easier than you think

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
			ftpClient.connect("localhost");

			// login to ftp server
			result = ftpClient.login("", "");
			if (result == true) {
				System.out.println("Successfully logged in!");
			} else {
				System.out.println("Login Fail!");
				return;
			}
			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 !");
			}
			ftpClient.logout();
		} catch (FTPConnectionClosedException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
				ftpClient.disconnect();
			} catch (FTPConnectionClosedException e) {
				System.err.println(e);
			}
		}
	}
}