javaftptimestampapache-commons-net

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


I am trying to fetch last modified date of a file from FTP environment.The result is not as expected.

By using ftpClient.getModificationTime("File path") I am getting null.

By using FTPFile.getTimestamp().getTime() I am getting wrong last modified (i.e. real last modified is of today and I am getting Wed Feb 18 02:55:22 EST 2004).

How to get correct last modified?

File at FTP

Thanks in advance.


Solution

  • FTPClient.getModificationTime returns null when the server returns an error response to MDTM command. Typically that would mean either that:

    Check FTPClient.getReplyString().


    If it turns out that the FTP server does not support MDTM command, you will have to use another method to retrieve the timestamps. If MDTM is not supported, MLSD won't be either.

    In that case the only other way is using LIST command to retrieve listing of all files and lookup the file you need - Use FTPClient.listFiles().

    FTPFile[] remoteFiles = ftpClient.listFiles(remotePath);
    
    Arrays.sort(remoteFiles,
        Comparator.comparing((FTPFile remoteFile) -> remoteFile.getTimestamp()).reversed());
    
    FTPFile latestFile = remoteFiles[0];
    System.out.println(
        "Latest file is " + latestFile.getName() +
        " with timestamp " + latestFile.getTimestamp().getTime().toString());
    

    See also Make FTP server return files listed by timestamp with Apache FTPClient.