Checking Directory existence on Ftp Server

In this section, you will learn how to check existence of a directory on the server by using java.

Checking Directory existence on Ftp Server

Checking Directory existence on Ftp Server

In this section, you will learn how to check existence of a directory on the server by using java.

Check existence of a Directory :

You can check the existence of a directory on FTP server. FTPClient class helps to list all the files and directory on the FTP server by using method listFile(). By using isDirectory() method of FTPFile class, you can check for directory.

Here is some steps to check existence of a directory -

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 iterate the files and put condition to check for directory.

for (FTPFile file : files) {
if (
file.isDirectory())
.....

 boolean isDirectory() method of FTPFile class returns true if directory found otherwise false.

Example :

In this example, we are checking for directory on FTP server.

Complete code is -

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 FtpCheckDirectory {
	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 count = 0;
			System.out.println("Checking directory existence on the server ... ");
			for (FTPFile file : files) {
				String fileStr=file.getName();
				if(fileStr.equals(".") || fileStr.equals("..")){
					continue;
				}
				if (file.isDirectory()) {
					count++;
				}
			}

			if (count > 0) {
				System.out.println(count + " directory found on FTP server.");
			} else {
				System.out.println("Sorry! There is no directory found 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.
Checking directory existence on the server ... 
2 directory found on FTP server.