如何在 Java 中使用 SFTP 获取目录的最新文件?



我正在尝试使用 SFTP 获取目录的最新文件。当目录中只有一个文件时,下面的代码给出了正确的最新文件。如果一段时间后在目录中创建了一个新文件,如果我再次运行下面的代码,它没有给出正确的最新文件,它会返回相同的旧文件。(要运行下面的代码,我正在使用计时器调度程序(。

//to have List of all the files of particular directory
List<File> files1 = new ArrayList<File>();  
Vector<LsEntry> files = sftpChannel.ls(filePath+"*.csv");
for (LsEntry entry : files)
{
if (!entry.getFilename().equals(".") && !entry.getFilename().equals(".."))
{
File f=new File(entry.getFilename());
files1.add(f);
}
}  
System.out.println("files length "+files1.size());
File[] files2=files1.toArray(new File[files1.size()]);  
long lastMod = Long.MIN_VALUE;
File choice = null;
for (File file : files2) {
if (file.lastModified() > lastMod) {
choice = file;
lastMod = file.lastModified();
}
}
lastModifiedFile=choice;

我什至尝试使用以下代码。它也没有提供正确的最新文件。

if (files2.length > 0) {
//** The newest file comes first 
Arrays.sort(files2, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
lastModifiedFile = files2[0];
}

它可以用集合或流来完成,因为 Vector.class 完全可以与 Java-Collections 竞争:

Vector<LsEntry> list = channelSftp.ls(filePath + "*.csv");
ChannelSftp.LsEntry lastModifiedEntry = Collections.max(list,
(Comparator.comparingInt(entry-> entry.getAttrs().getMTime()))
);

LsEntry lastModifiedEntry = list.stream().max(
Comparator.comparingInt(entry -> entry.getAttrs().getMTime())
).get();

使用LsEntry.getAttrs().getMTime()查询 SFTP 服务器上文件的修改时间。

Vector<LsEntry> files = channelSftp.ls(filePath + "*.csv");
LsEntry newestEntry = null;
for (LsEntry entry : files)
{
if (!entry.getFilename().equals(".") && !entry.getFilename().equals(".."))
{
if ((newestEntry == null) ||
(newestEntry.getAttrs().getMTime() < entry.getAttrs().getMTime()))
{
newestEntry = entry;
}
}
}
if (newestEntry != null)
{
System.out.println(
"Newest file is " + newestEntry.getFilename() +
" with timestamp " + newestEntry.getAttrs().getMtimeString());
}

解释代码不起作用的原因:仅将文件名复制到File列表中,因此file.lastModified()无法返回任何相关值。此外,File对象设计为仅处理本地文件。

最新更新