Sometimes we need to know whether a directory or a file exists on a FTP server before doing further operation. This article explains how to do that in Java with the help of Apache Commons Net library.

To detect if a directory or file exists, we can check server’s reply code. According to FTP protocol specification, the FTP server returns code 550 when a requested file or directory is unavailable. So the code to check would look like this:

// invokes an operation for a file/diretory...
// checks reply code:
int returnCode = ftpClient.getReplyCode();
if (returnCode == 550) {
    // file/directory is unavailable
}

Let’s dive into detail for each case.

 

Determine if a directory exists:

To check existence of a specific directory:

-          Try to change the working directory to that directory.

-          Check reply code from the server

Here is example code:

boolean checkDirectoryExists(String dirPath) throws IOException {
    ftpClient.changeWorkingDirectory(dirPath);
    returnCode = ftpClient.getReplyCode();
    if (returnCode == 550) {
        return false;
    }
    return true;
}

NOTE: If the specified directory does exist, consider switching the working directory back to the last one, because the method above will change to working directory if the specified directory exists.

 

Determine if a file exists:

To check existence of a specific file:

-          Try to retrieve an input stream of that file.

-          Check reply code from the server.

Here is example code:

boolean checkFileExists(String filePath) throws IOException {
    InputStream inputStream = ftpClient.retrieveFileStream(filePath);
    returnCode = ftpClient.getReplyCode();
    if (inputStream == null || returnCode == 550) {
        return false;
    }
    return true;
}

 

Java Example program to check file/directory exists on FTP server:

For demonstration purpose, we create a sample program that logins to a FTP server, then checks for existence of a directory and a file, and finally logs out from the server. Here is the code:

package net.codejava.ftp;

import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

/**
 * This program demonstrates how to determine existence of a specific
 * file/directory on a remote FTP server.
 * @author www.codejava.net
 *
 */
public class FTPCheckFileExists {
	private FTPClient ftpClient;
	private int returnCode;

	/**
	 * Determines whether a directory exists or not
	 * @param dirPath
	 * @return true if exists, false otherwise
	 * @throws IOException thrown if any I/O error occurred.
	 */
	boolean checkDirectoryExists(String dirPath) throws IOException {
		ftpClient.changeWorkingDirectory(dirPath);
		returnCode = ftpClient.getReplyCode();
		if (returnCode == 550) {
			return false;
		}
		return true;
	}

	/**
	 * Determines whether a file exists or not
	 * @param filePath
	 * @return true if exists, false otherwise
	 * @throws IOException thrown if any I/O error occurred.
	 */
	boolean checkFileExists(String filePath) throws IOException {
		InputStream inputStream = ftpClient.retrieveFileStream(filePath);
		returnCode = ftpClient.getReplyCode();
		if (inputStream == null || returnCode == 550) {
			return false;
		}
		return true;
	}

	/**
	 * Connects to a remote FTP server
	 */
	void connect(String hostname, int port, String username, String password)
			throws SocketException, IOException {
		ftpClient = new FTPClient();
		ftpClient.connect(hostname, port);
		returnCode = ftpClient.getReplyCode();
		if (!FTPReply.isPositiveCompletion(returnCode)) {
			throw new IOException("Could not connect");
		}
		boolean loggedIn = ftpClient.login(username, password);
		if (!loggedIn) {
			throw new IOException("Could not login");
		}
		System.out.println("Connected and logged in.");
	}

	/**
	 * Logs out and disconnects from the server
	 */
	void logout() throws IOException {
		if (ftpClient != null && ftpClient.isConnected()) {
			ftpClient.logout();
			ftpClient.disconnect();
			System.out.println("Logged out");
		}
	}

	/**
	 * Runs this program
	 */
	public static void main(String[] args) {
		String hostname = "www.yourserver.com";
		int port = 21;
		String username = "your_user";
		String password = "your_password";
		String dirPath = "Photo";
		String filePath = "Music.mp4";

		FTPCheckFileExists ftpApp = new FTPCheckFileExists();

		try {
			ftpApp.connect(hostname, port, username, password);

			boolean exist = ftpApp.checkDirectoryExists(dirPath);
			System.out.println("Is directory " + dirPath + " exists? " + exist);

			exist = ftpApp.checkFileExists(filePath);
			System.out.println("Is file " + filePath + " exists? " + exist);

		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			try {
				ftpApp.logout();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
}

 

Related Java FTP Tutorials:

 

Other Java FTP Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Attachments:
Download this file (FTPCheckFileExists.java)FTPCheckFileExists.java[sample program]2 kB

Add comment

   


Comments 

#6Sudheer2022-03-07 05:22
Thanks for the program, When I am running your program I am getting 425 return code in checkFileExists method. Could you please help on this
Quote
#5Marco2017-07-28 10:07
Quoting Robert Griffiths:
I found I needed to add a call to completePendingCommand() after the retrieveFileStream to ensure the next file existence check worked. Without it, the next call to the ftp server always failed.

Thank you bro, you saved me my day!!!
Quote
#4Nam2015-08-13 16:07
Thanks wIndouflo and cagri for your nice suggestions.
Quote
#3cagri2015-08-13 09:14
This is better.
boolean checkFileExists(String filePath, FtpSession ftpSession) throws IOException {
FTPFile[] result = ftpSession.list(filePath);
return result.length > 0;
}
Quote
#2wIndouflo2015-06-12 07:59
Method checkDirectoryExists doesn't work in this state: completePendingCommand() must be called, the stream must be closed:

public boolean checkFileExists(String filename) {
InputStream inputStream = mFtpsClient.retrieveFileStream(filename);
boolean fileExists = inputStream != null && mFtpsClient.getReplyCode() != 550;
if (inputStream != null) {
inputStream.close();
mFtpsClient.completePendingCommand();
}
return fileExists;
}
Quote