java获取sftp文件,使用Java查找SFTP最旧文件的文件大小和最后修改

这篇博客介绍了如何利用JSch库从SFTP服务器获取最旧的XML文件,并确保在下载前文件未被写入。作者首先找到最旧的文件,然后检查其大小,等待一段时间后再确认大小是否变化,以此判断文件是否安全可下载。如果文件大小不变,则进行下载和处理。
摘要由CSDN通过智能技术生成

I'm using JSch to get files from an SFTP server, but I'm trying to figure out a way to only get the oldest file, and to make sure that it is not currently being written to. The way I imagine myself doing this is first finding which file in the specified remote folder is oldest. I would then check the file size, wait x seconds (probably about 10, just to be safe) and then check it again. If the file size has not changed, I download the file and process it. However, I have no idea how to do this! If anybody knows how to do this, or knows of something else that supports SFTP that has this built-in (I know Apache Commons does, but only does FTPS), it would be greatly appreciated.

Thanks in advance.

解决方案

Turns out that this is entirely possible in JSch, the hardest part is simply finding the documentation. Code I used is below, hopefully somebody else will find it helpful! (I'm sure there are optimizations to be made, I know, I know. There are also variables that are defined elsewhere, but hopefully anybody that needs this will be able to figure them out!)

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;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值