Java FTP list files and directories example
- Details
- Written by Nam Ha Minh
- Last Updated on 20 July 2019   |   Print Email
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:
Related Java FTP Tutorials:
- List files and directories recursively on a FTP server
- Java FTP example - Search for files and directories
- Creating nested directory structure on a FTP server
- Java FTP example - Calculate total sub directories, files and size of a directory
- Determine if a directory or file exists on FTP server
- Remove an empty directory on a FTP server
- Rename file or directory on FTP server
Other Java FTP Tutorials:
- Connect and login to a FTP server
- Java FTP create directory example
- Java FTP file download tutorial and example
- Java FTP file upload tutorial and example
- Java FTP delete file example
- How to upload a directory to a FTP server
- How to download a complete folder from a FTP server
Comments
Thank you very much for sharing this. I have the same Problem here.
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);
org.eclipse.debug.core.DebugException: com.sun.jdi.ClassNotLoadedException: Type has not been loaded occurred while retrieving component type of array.
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)