Use of FTPClient

In this section we will discuss about use of FTPClient class with example.

Use of FTPClient

Use of FTPClient

In this section we will discuss about use of FTPClient class with example.

FTPClient :

FTPClient class is defined in org.apache.commons.net.ftp package. It holds all the necessary functionality for handling operations of FTP Server. This class is responsible for all initial phases of FTP server and also supplies high level interface to the server. FTPClient provides various methods to communicate with FTP server and performing different kinds of operations.

Use of FTPClient : FTPClient class is very useful for handling operations of  FTP server  like connecting to the server, login to the server by authenticating the valid user, uploading, downloading files, listing files and directories, creating new directory etc..

Some methods of FTPClient -

login(String username, String password) : This method is used to login to the ftp server and it uses username and password to check for valid user.

listDirectories() : This method is used to list the directories of the current working directory.

listDirectories(String parent) : Lists all the directories of the mentioned directory.

listFiles() : This method of FTPClient lists all the file information of the current working directory.

listNames() : This method is used to find the filename in the working directory.

logout() : It is used to quit the FTP server.

storeFile(String remote, InputStream local) : It is used for uploading the files to the server.

There are many more methods for performing different kind of operations on FTP server.

Example : Here we are giving you a simple usage of FTPClient class method. This program lists directory names of the current working directory of server.

import java.io.IOException;

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

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

			if (result == true) {
				System.out.println("User successfully logged in.");
			} else {
				System.out.println("Login failed!");
				return;
			}
			FTPFile[] files = client.listDirectories();
			System.out
					.println("Directories on current working directory of Ftp : ");
			for (FTPFile file : files) {
				System.out.println(file.getName());
			}

		} catch (FTPConnectionClosedException e) {
			System.out.println(e);
		} finally {
			try {
				client.disconnect();
			} catch (FTPConnectionClosedException e) {
				System.out.println(e);
			}
		}
	}
}

Output :

User successfully logged in.
Directories on current working directory of Ftp : 
.
..
filetest
test
upload123