如何保留使用Apache FTPClient检索文件时修改的日期?

我正在使用org.apache.commons.net.ftp.FTPClient从ftp服务器检索文件。 在文件保存在我的机器上时,保留文件的最后修改时间戳至关重要。 有没有人建议如何解决这个问题?

这就是我解决它的方式:

 public boolean retrieveFile(String path, String filename, long lastModified) throws IOException { File localFile = new File(path + "/" + filename); OutputStream outputStream = new FileOutputStream(localFile); boolean success = client.retrieveFile(filename, outputStream); outputStream.close(); localFile.setLastModified(lastModified); return success; } 

我希望Apache团队能够实现这一function。

这是你如何使用它:

 List ftpFiles = Arrays.asList(client.listFiles()); for(FTPFile file : ftpFiles) { retrieveFile("/tmp", file.getName(), file.getTimestamp().getTime()); } 

您可以在下载文件后修改时间戳。

可以通过LIST命令或(非标准)MDTM命令检索时间戳。

你可以在这里看到如何修改时间戳: http : //www.mkyong.com/java/how-to-change-the-file-last-modified-date-in-java/

下载文件列表(如FTPClient.mlistDirFTPClient.listFiles返回的所有文件)时,请使用随列表返回的时间戳来更新本地下载文件的时间戳:

 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()); } 

仅下载单个特定文件时,请使用FTPClient.mdtmFile检索远程文件时间戳并相应地更新下载的本地文件的时间戳:

 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()); }