gpt4 book ai didi

java - 使用 Java 查找 SFTP 最旧文件的文件大小和最后修改时间

转载 作者:行者123 更新时间:2023-12-02 08:29:26 24 4
gpt4 key购买 nike

我正在使用 JSch 从 SFTP 服务器获取文件,但我正在尝试找出一种方法来仅获取最旧的文件,并确保它当前未被写入。我想象自己这样做的方式是首先查找指定远程文件夹中最旧的文件。然后我会检查文件大小,等待 x 秒(可能大约 10 秒,只是为了安全起见),然后再次检查。如果文件大小没有改变,我会下载文件并处理它。但是,我不知道该怎么做!如果有人知道如何做到这一点,或者知道其他支持内置此功能的 SFTP(我知道 Apache Commons 可以,但只有 FTPS),我们将不胜感激。

提前致谢。

最佳答案

事实证明,这在 JSch 中是完全可能的,最难的部分就是找到文档。我使用的代码如下,希望其他人会发现它有帮助! (我确信需要进行优化,我知道,我知道。还有其他地方定义的变量,但希望任何需要它的人都能够弄清楚它们!)

public static String oldestFile() {
Vector list = null;
int currentOldestTime;
int nextTime = 2140000000; //Made very big for future-proofing
ChannelSftp.LsEntry lsEntry = null;
SftpATTRS attrs = null;
String nextName = null;
try {
list = Main.chanSftp.ls("*.xml");
if (list.isEmpty()) {
fileFound = false;
}
else {
lsEntry = (ChannelSftp.LsEntry) list.firstElement();
oldestFile = lsEntry.getFilename();
attrs = lsEntry.getAttrs();
currentOldestTime = attrs.getMTime();
for (Object sftpFile : list) {
lsEntry = (ChannelSftp.LsEntry) sftpFile;
nextName = lsEntry.getFilename();
attrs = lsEntry.getAttrs();
nextTime = attrs.getMTime();
if (nextTime < currentOldestTime) {
oldestFile = nextName;
currentOldestTime = nextTime;
}
}
attrs = chanSftp.lstat(Main.oldestFile);
long size1 = attrs.getSize();
System.out.println("-Ensuring file is not being written to (waiting 1 minute)");
Thread.sleep(60000); //Wait a minute to make sure the file size isn't changing
attrs = chanSftp.lstat(Main.oldestFile);
long size2 = attrs.getSize();
if (size1 == size2) {
System.out.println("-It isn't.");
fileFound = true;
}
else {
System.out.println("-It is.");
fileFound = false;
}
}
} catch (Exception ex) {ex.printStackTrace();}
return Main.oldestFile;
}

关于java - 使用 Java 查找 SFTP 最旧文件的文件大小和最后修改时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2641286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com