Pages Navigation Menu

Coding is much easier than you think

List Files and Directories on FTP server

 
listFiles() : This method of FTPClient is used to list all files and directories of the current FTP server directory. This method returns array of FTPFile object which list the files and directories.

FTPFile[] files = client.listFiles();

FTPFile class supply many methods which is used to handle file and directories like getName(), getSize(), isDirectory(), isFile(), getTimestamp().

Example : In this example we are listing all the files and directories of FTP server and displaying the same.

 

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 FTPListFiles
{
	public static void main(String[] args) throws IOException
        {
	FTPClient client = new FTPClient();
	boolean result;
	try
        {
		client.connect("localhost");
		result = client.login("admin", "admin");
		client.changeWorkingDirectory("c:/FTP");
		if (result == true)
                {
			System.out.println("Logged in Successfully !");
		}
                else
                {
			System.out.println("Login failed !");
			return;
		}
		FTPFile[] files = client.listFiles();
		System.out.println("Files and directories on Ftp Server directory : ");
		for (FTPFile file : files)
                {
			System.out.println(file.getName());
		}

	}
 
        catch (FTPConnectionClosedException e)
        {
		System.out.println(e);
	}
        finally
        {
	try
        {
	client.disconnect();
	}
        catch (FTPConnectionClosedException e)
        {
			System.out.println(e);
	}
	}
	}
}

 

Output :

 

Logged in Successfully !
Files and directories on Ftp Server directory :

FtpTutorial
FTPListFiles.java
filetest
simplecodesuffs
FtpConnect.java
Ftp.doc

One Comment

  1. Dear Friends,
    I want some basic and very simple project in jsp +mysql. step by step explanation