Home Java Javaftp Search file on Ftp Server
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Search file on Ftp Server

Advertisement
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 {
			client.connect("localhost");
			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 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;
					break;
				} else {
					flag = 0;
				}
			}

			if (flag == 1) {
				System.out.println("File exists on FTP server. ");
			} else {
				System.out
						.println("Sorry! your file is not presented 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 file existence on the server ... 
File exists on FTP server. 
Advertisement

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

Ask Questions?    Discuss: Checking file existence on Ftp Server  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com