Java FTP Check if a directory or file exists on server
- Details
- Written by Nam Ha Minh
- Last Updated on 19 July 2019   |   Print Email
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:
- Java FTP create directory example
- Java FTP example - Change working directory
- Creating nested directory structure on a FTP server
- Remove an empty directory on a FTP server
- Rename file or directory on FTP server
Other Java FTP Tutorials:
- Connect and login to a FTP server
- Java FTP list files and directories example
- Java FTP file download tutorial and example
- Java FTP file upload tutorial and example
- Java FTP delete file example
- Java FTP example - Search for files and directories
- How to upload a directory to a FTP server
- How to download a complete folder from a FTP server
Comments
Thank you bro, you saved me my day!!!
boolean checkFileExists(String filePath, FtpSession ftpSession) throws IOException {
FTPFile[] result = ftpSession.list(filePath);
return result.length > 0;
}
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;
}