Pages Navigation Menu

Coding is much easier than you think

Search 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))

 
File : FtpCheckFile.java
 

package com.simplecode.net;

import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPConnectionClosedException;

class FtpCheckFile {
	public static void main(String[] args) throws IOException {
	FTPClient ftpclient = new FTPClient();
	boolean result;
	try {

		// Connect to the localhost

		ftpclient.connect("localhost");

		// login to ftp server

		result = ftpclient.login("admin", "admin");

		if (result == true) {
			System.out.println("User logged in successfully !");
		} else {
			System.out.println("Login failed !");
			return;
		}
		FTPFile[] files = ftpclient.listFiles();
		int flag = 0;
		String checkFile = "FindFtp.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.err.println(e);
	} finally {
		try {
			ftpclient.disconnect();
		} catch (FTPConnectionClosedException e) {
			System.err.println(e);
		}
	}
	}
}