Search Directory on Ftp Server

This tutorial describes how to search a specific directory on the server by using java.

Search Directory on Ftp Server

Search Directory on Ftp Server

This tutorial describes how to search a specific directory on the server by using java.

Find Directory on server :

For searching any directory on the FTP server, FTP Client class and FTP File class is very helpful. You can easily search the specified named directory on the ftp server by following the below steps-

1. Connect and login to the FTP server.

client.connect("localhost");
client.login("admin", "admin");

2. List all the files and directories of FTP server and store on FTPFile array.

FTPFile[] files = client.listFiles();

3. Now search the given directory by iterating the files and checking each time for that.

for (FTPFile file : files) {
String fileName = file.getName();
if (fileName.equals(searchDir))
.....

Example :

In this example we are searching directory "ftptest" on the server. First listing all the files and directory by using FTPClient method client.listFiles() and store all in FTPFile array. Now iterate the files and get name of file by calling file.getName() of FTPFile. Next put check condition that given file is equal to the list files or not. If found then break the loop and print "Directory exists on FTP server. "

Code -

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 FtpSearchDirectory {
	public static void main(String[] args) throws IOException {
		FTPClient client = new FTPClient();
		boolean result;
		try {
			// Connect to the localhost
			client.connect("localhost");

			// login to ftp server
			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.listFiles();
			int flag = 0;
			String searchDir = "filetest";
			System.out.println("Searching directory '" + searchDir
					+ "' on the server ... ");
					
			//Searching directory in list of files
			for (FTPFile file : files) {
				String fileName = file.getName();
				if (fileName.equals(searchDir)) {
					flag = 1;
					break;
				} else {
					flag = 0;
				}
			}

			if (flag == 1) {
				System.out.println("Directory exists on FTP server. ");
			} else {
				System.out.println("Sorry! specified directory is not presented on Ftp server.");
			}

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

Output :

User successfully logged in.
Searching directory 'filetest' on the server ... 
Directory exists on FTP server.