How to preserve date modified when retrieving file using Apache FTPClient?

前端 未结 3 1113
情歌与酒
情歌与酒 2021-01-14 02:36

I am using org.apache.commons.net.ftp.FTPClient for retrieving files from a ftp server. It is crucial that I preserve the last modified timestamp on the file wh

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-14 03:33

    When download list of files, like all files returned by by FTPClient.mlistDir or FTPClient.listFiles, use the timestamp returned with the listing to update timestemp of local downloaded files:

    String remotePath = "/remote/path";
    String localPath = "C:\\local\\path";
    
    FTPFile[] remoteFiles = ftpClient.mlistDir(remotePath);
    for (FTPFile remoteFile : remoteFiles) {
        File localFile = new File(localPath + "\\" + remoteFile.getName());
        
        OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFile));
        if (ftpClient.retrieveFile(remotePath + "/" + remoteFile.getName(), outputStream))
        {
            System.out.println("File " + remoteFile.getName() + " downloaded successfully.");
        }
        outputStream.close();
        
        localFile.setLastModified(remoteFile.getTimestamp().getTimeInMillis());
    }
    

    When downloading a single specific file only, use FTPClient.mdtmFile to retrieve the remote file timestamp and update timestamp of the downloaded local file accordingly:

    File localFile = new File("C:\\local\\path\\file.zip");
    FTPFile remoteFile = ftpClient.mdtmFile("/remote/path/file.zip");
    if (remoteFile != null)
    {
        OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFile));
        if (ftpClient.retrieveFile(remoteFile.getName(), outputStream))
        {
            System.out.println("File downloaded successfully.");
        }
        outputStream.close();
    
        localFile.setLastModified(remoteFile.getTimestamp().getTimeInMillis());
    }
    

提交回复
热议问题