我正在使用
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 团队能够实现这个功能。
这就是你如何使用它:
List<FTPFile> 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.mlistDir
或 FTPClient.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());
}