get latest file from ftp

后端 未结 2 635
逝去的感伤
逝去的感伤 2021-01-17 18:54

Trying to create a simple plugin that simply connects to an ftp site, looks up the latest file and then downloads it. However, it isn\'t getting the latest file.

I\'

相关标签:
2条回答
  • 2021-01-17 19:05

    I see only one mistake:

    FTPFile choice = null;
    

    If the first file were the latest modified file, then the method would return null, causing a potential NullPointerException.

    Change it to

    FTPFile choice = files[0];
    

    and the logic should be right.

    If it still doesn't return the expected file, then most likely the file in question simply doesn't have the expected last modified date. Add something like this to the for loop in the method:

    System.out.println(file.getTimestamp().getTime() + " - " + file.getName());
    

    And look closer.

    0 讨论(0)
  • 2021-01-17 19:07

    Instead of your "lastFileModified" method, I would create a Comparator. It would be easier to write the sort method:

    public class LastModifiedComparator implements Comparator<FTPFile> {
    
        public int compare(FTPFile f1, FTPFile f2) {
            return f1.getTimestamp().compareTo(f2.getTimeStamp());
        }
    }
    

    Then, getting the "last" FTPFile is much easier:

    public FTPFile getMaxLastModified(FTPFile[] ftpFiles) {
        return Collections.max(Arrays.asList(ftpFiles), new LastModifiedComparator());
    }
    

    To come back to your problem: the "lastModified" timestamp is not linked to the FTP upload order. When you upload a file through the FTP protocol, the original timestamp of the file may be preserved.

    So, if file1 is older than file2, your method will always return file2, even if file2 is uploaded before file1 on the FTP server.

    I think that it is impossible to determine the last uploaded file. This information is not stored by the FTP protocol. You can do that only if you overload the "put" method of your FTP client:

    public void put(File file) {
        // upload code
        FTPFile ftpFile = getJustUploadedFile(file);
        ftpFile.setTimestamp(new Calendar()); // Now! 
    }
    
    0 讨论(0)
提交回复
热议问题