Home Java Javaftp Search file on Ftp Server

Related Tutorials


Share on Google+Share on Google+

Search file on Ftp Server

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

Search file on Ftp Server

In this section, you will learn how to search a file on the server by using java.

Find File on FTP server : If you want to check existence of any file on the server, FTPClient class helps you to find the file by providing various methods. For that we need the file name which we want to search.

Here is some steps to check existence of any file -

1. List all the files in the ftp server by using method listFiles() as - FTPFile[] files = client.listFiles();

2.  Take the searched file as a String variable. String checkFile = FtpTest.txt";

3. Iterate all the files of ftp server and check it matches to the searched file name or not. if (fileName.equals(checkFile))

Example : This example demonstrate the above steps -

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 FtpCheckFile {
	public static void main(String[] args) throws IOException {
		FTPClient client = new FTPClient();
		boolean result;
		try {
			result = client.login("admin", "admin");

			if (result == true) {
				System.out.println("User successfully logged in.");
			} else {
				System.out.println("Login failed!");
			FTPFile[] files = client.listFiles();
			int flag = 0;
			String checkFile = "FtpTest.txt";
			System.out.println("Checking file existence on the server ... ");
			for (FTPFile file : files) {
				String fileName = file.getName();
				if (fileName.equals(checkFile)) {
					flag = 1;
				} else {
					flag = 0;

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

		} catch (FTPConnectionClosedException e) {
		} finally {
			try {
			} catch (FTPConnectionClosedException e) {

Output :

User successfully logged in.
Checking file existence on the server ... 
File exists on FTP server. 

If you enjoyed this post then why not add us on Google+? Add us to your Circles

Liked it!  Share this Tutorial

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 8, 2012

Related Tutorials

Discuss: Checking file existence on Ftp Server  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image