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:

    • FTPFile[] listDirectories()
    • FTPFile[] listDirectories(String parent)
    • FTPFile[] listFiles()
    • FTPFile[] listFiles(String pathname)
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:

    • String getName():returns name of the file or directory.
    • long getSize():return size in bytes.
    • boolean isDirectory():determines if the entry is a directory.
    • boolean isFile():determines if the entry is a file.
    • Calendar getTimestamp():returns last modified time.
The FTPClient class also has two simple methods for listing files and directories:

    • String[] listNames()
    • String[] listNames(String pathname)
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

Add comment

   


Comments 

#13Markus2022-02-10 03:47
Quoting Thanh Nguyen:

FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
ftpClient.configure(config);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);


Thank you very much for sharing this. I have the same Problem here.
Quote
#12Thanh Nguyen2019-10-20 04:01
When testing your code, it was stuck at
   FTPFile[] files1 = ftpClient.listFiles("/public_ftp");
I have to make some configuration like this and it works well :
FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
ftpClient.configure(config);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
Quote
#11Rajesh2019-06-05 13:33
Getting below exception on execution - Could you please help.
org.eclipse.debug.core.DebugException: com.sun.jdi.ClassNotLoadedException: Type has not been loaded occurred while retrieving component type of array.
Quote
#10deepanker2018-08-30 03:05
use latest version of jar .This will solve your problem
Quote
#9ga2018-08-23 08:02
run:
Exception in thread "main" java.net.UnknownHostException: ftpupload.net
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
Quote