How to get a directory listing

There are two basic ways to get a list of the files in a particular directory on an FTP server. The simpler way gets the names of the files using the dir() method:

This results in the files array containing the name of the files and directories in the current working directory on the server.

FTP servers can return more information than just the names of the files and directories. This information can be returned as an array of strings by using an overloaded dir() method. The 'full' boolean flag must be set to true to get the full listing:

string[] descriptions = ftp.dir("mydirname", true);

For convenience, the detailed file and directory information can be interpreted and returned as an object, in the dirDetails() method:

FTPFile[] files = ftp.dirDetails(".");

This method returns an array of FTPFile objects containing information about the files in the directory - details such as the size of the file and whether or not it is a directory.

If a listing of a directory other than the current working directory is required it is recommended that the remote working directory be changed to that directory, as described in How to change directories. The relative or absolute path may be passed to either method, but some FTP servers do not support this feature. In these cases changing directories should work.

Changing locale

Sometimes the dirDetails() method will fail with a ParseException, citing a date string that it cannot interpret. This is usually because the FTP server is in a different locale to the client. It may be returning month names that cannot be understood in the client's locale. For example, an FTP server in a German locale will return German month names, which cannot be interpreted by a client in a locale that uses English. To solve this, the server's locale should be set in the client, via the setParserLocale method:

ftp.setParserLocale(Locale.GERMAN);

Custom parsers

Unix, Windows and VMS file listing parsers are supplied and should cover most scenarios. If a server is encountered that does not have a supported format, a custom parser can be written for that server. To do this, the FTPFileParser interface must be implemented. Contact EDT if you would like a custom parser written for you. To force the use of this parser (or of an existing parser), use:

ftp.setFTPFileFactory(new FTPFileFactory(new MyCustomerParser()));

All methods described above are supported in the FTPClient, SSLFTPClient, and ProFTPClient classes. Note that setParserLocale is not supported in the SSHFTPClient class.