Make FTP server return files listed by timestamp with Apache FTPClient

旧街凉风 提交于 2019-11-28 11:44:31

There's no standard way to have the FTP server sort the files according to your (or any) criteria.

Though some FTP servers, notably the ProFTPD and vsftpd, support proprietary flags with the LIST command to sort the entries.

Both these servers support the -t flag to sort the files by a modification time:

LIST -t

Though this is not only non-standard, it actually violates the FTP protocol.

For all options supported by ProFTPD, see its man page:
http://www.proftpd.org/docs/directives/linked/config_ref_ListOptions.html

Note that vsftpd supports only -a, -r, -t, -F and -l with the same meaning as ProFTPD.

The Apache Commons Net has no API to add flags to the LIST command (the only exception, while irrelevant to this question, is the -a flag - which is sent when FTPClient.setListHiddenFiles is set).

You would have to override the FTPClient.getListArguments to inject your own flags.


Though again, I do not see what's wrong with using Comparator to sort the files. Just make sure you use FTPClient.mlistDir(), which internally uses a modern MLSD command. This way you get precise timestamps, not minute- or worse precision timestamps like with obsolete LIST - FTPClient.listFiles().

FTPFile[] remoteFiles = ftpClient.mlistDir(remotePath);

Arrays.sort(remoteFiles,
    Comparator.comparing((FTPFile remoteFile) -> remoteFile.getTimestamp()).reversed());

Though, as you commented, the vsftpd does not support MLSD (ProFTPD does). In that case the LIST -t is indeed the only efficient (although again, not standard/portable) way to get precisely sorted files. Except for a time-consuming call of MDTM - FTPClient.getModificationTime for each listed file. If you can do without precise timestamps, the same code as above, but with FTPClient.listFiles() will do.

See also Fetching last modified date of a file in FTP server using FTPClient.getModificationTime yields null.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!