Sample code for 30+ languages & platforms
Java

Directory Existence Check

See more FTP Examples

How to test if a directory exists on an FTP server.

A good way to check to see if a directory already exists is to try to "cd" to that remote directory by calling ChangeRemoteDir. If it succeeds, then the directory exists. If not, then it does not exist. An alternative method is to set the ListPattern = "*" and then iterate over the files/directories, looking for the directory.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Ftp2;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example requires the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        Ftp2 ftp = new Ftp2();

        ftp.setHostname("ftp.example.com");
        ftp.setUsername("login");
        ftp.setPassword("password");

        // Connect and login to the FTP server.
        try {
            ftp.connect();
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Does the "temp" directory exist?
        boolean dirExists = false;
        try {
            ftp.changeRemoteDir("/temp");
            dirExists = true;
        } catch (ChilkatException e) {
            dirExists = false;
        }
        if (dirExists) {
            System.out.println("Yes, the temp directory exists.");
            //  Yes, it exists. Restore the current remote dir:
            try {
                ftp.changeRemoteDir("..");
            } catch (ChilkatException e) {
                System.out.println(e.getLastErrorText());
                return;
            }
        }

        // Alternatively, you may set the ListPattern = "*" and
        //  look for the directory:
        ftp.setListPattern("*");

        int n = ftp.getDirCount();
        if (n < 0) {
            // Failed to get directory listing based on ListPattern
            System.out.println(ftp.getLastErrorText());
            return;
        }

        if (n > 0) {
            for (int i = 0; i < n; i++) {
                boolean isDir = ftp.getIsDirectory(i);
                if (isDir) {
                    String fname = ftp.getFilename(i);
                    if ("temp".equals(fname)) {
                        System.out.println("Found temp directory!");
                        ftp.disconnect();
                        return;
                    }
                }
            }
        }

        ftp.disconnect();
    }
}