This article describes steps for listing content of a directory on a FTP server using Apache Commons Net API. If you have not been familiar with FTP programming in Java before, it is recommended to read this article: How to start FTP programming with Java

 

1. The Apache Commons NET’s FTP API for listing files and directories

The FTPClient class provides the following methods for listing content of a directory on the FTP server:

The differences of these methods are described in the following comparison table:

Method

List files?

List directories?

List in current working directory?

List in a specified directory?

listDirectories()

No

Yes

Yes

No

listDirectories(String parent)

No

Yes

No

Yes

listFiles()

Yes

Yes

Yes

No

listFiles(String pathname)

Yes

Yes

No

Yes

 

All the above methods return an array of FTPFile objects which represent files and directories. The FTPFile class provides various methods for querying detailed information of a file or directory, to name some useful ones:

The FTPClient class also has two simple methods for listing files and directories:

Unlike the listFiles() and listDirectories() methods, the listNames()methods simply return an array of String represents file/directory names; and they list both files and directories.

 

2. Java FTP File and Directory Listing Code Examples



The following code snippet demonstrates listing files and directories under the current working directory. The code must connect and login to the server before and logout then disconnect after:

FTPClient ftpClient = new FTPClient();
ftpClient.connect(server, port);
ftpClient.login(user, pass);

// lists files and directories in the current working directory
FTPFile[] files = ftpClient.listFiles();

// iterates over the files and prints details for each
DateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

for (FTPFile file : files) {
    String details = file.getName();
    if (file.isDirectory()) {
        details = "[" + details + "]";
    }
    details += "\t\t" + file.getSize();
    details += "\t\t" + dateFormater.format(file.getTimestamp().getTime());
    System.out.println(details);
}

ftpClient.logout();
ftpClient.disconnect();
You can try to use other methods for experimenting yourself:

FTPFile[] files = ftpClient.listFiles("/document");
FTPFile[] files = ftpClient.listDirectories("/images");
FTPFile[] files = ftpClient.listDirectories();
The following code snippet demonstrates usage of listNamesmethod:

String[] files = ftpClient.listNames();
if (files != null && files.length > 0) {
    for (String aFile: files) {
        System.out.println(aFile);
    }
}
 

3. Java FTP File and Directory Listing Demo program

Here is a fully working demo program that connects to a FTP server, queries content of public_ftp directory using listFiles() method; and show all files and directories under server’s root directory. Finally the program logs out and disconnects from the server:

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

/**
 * An example program that demonstrates how to list files and directories
 * on a FTP server using Apache Commons Net API.
 * @author www.codejava.net
 */
public class FTPListDemo {

	public static void main(String[] args) {
		String server = "www.ftpserver.com";
		int port = 21;
		String user = "username";
		String pass = "password";

		FTPClient ftpClient = new FTPClient();

		try {

			ftpClient.connect(server, port);
			showServerReply(ftpClient);

			int replyCode = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(replyCode)) {
				System.out.println("Connect failed");
				return;
			}

			boolean success = ftpClient.login(user, pass);
			showServerReply(ftpClient);

			if (!success) {
				System.out.println("Could not login to the server");
				return;
			}

			// Lists files and directories
			FTPFile[] files1 = ftpClient.listFiles("/public_ftp");
			printFileDetails(files1);

			// uses simpler methods
			String[] files2 = ftpClient.listNames();
			printNames(files2);


		} catch (IOException ex) {
			System.out.println("Oops! Something wrong happened");
			ex.printStackTrace();
		} finally {
			// logs out and disconnects from server
			try {
				if (ftpClient.isConnected()) {
					ftpClient.logout();
					ftpClient.disconnect();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

	private static void printFileDetails(FTPFile[] files) {
		DateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (FTPFile file : files) {
			String details = file.getName();
			if (file.isDirectory()) {
				details = "[" + details + "]";
			}
			details += "\t\t" + file.getSize();
			details += "\t\t" + dateFormater.format(file.getTimestamp().getTime());

			System.out.println(details);
		}
	}

	private static void printNames(String files[]) {
		if (files != null && files.length > 0) {
			for (String aFile: files) {
				System.out.println(aFile);
			}
		}
	}

	private static void showServerReply(FTPClient ftpClient) {
		String[] replies = ftpClient.getReplyStrings();
		if (replies != null && replies.length > 0) {
			for (String aReply : replies) {
				System.out.println("SERVER: " + aReply);
			}
		}
	}
}
Screenshot of compile and run the program under Windows:

compile and run FTP list dir program

 

 

Related Java FTP Tutorials:

 

Other Java FTP Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (FTPListDemo.java)FTPListDemo.java[Java FTP listing files demo program]2 kB