[英]Finding file size and last modified of SFTP oldest file using Java
我正在使用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;
}
您可以使用支持SFTP的edtFTPj / PRO輕松完成此操作。
只需獲取目錄列表,然后按日期對列表進行排序。 如果最舊的日期不在最后幾分鍾,您可以下載。
計算遠程服務器中的文件夾大小只需調用ftpFolderSize(ftpFolderSize,client)
目錄路徑,並將對象FTPClient
作為參數傳遞。 它將返回文件夾的大小。
僅適用於FTP。
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.io.FileUtils;
long dirSize = 0L; //global variable
private long ftpFolderSize(String directoryPath,FTPClient client){
try{
client.changeWorkingDirectory(directoryPath);
FTPFile[] ftpFiles = client.listFiles();
if(client.changeWorkingDirectory(directoryPath))
{
for (FTPFile ftpFile : ftpFiles) {
if(ftpFile.isFile()){
dirSize = dirSize+ftpFile.getSize();// file size is calculated
}
else if(ftpFile.isDirectory())
{
dirSize = dirSize + 4096;//folder minimum size is 4kb
ftpFolderSize(directoryPath+"/"+ftpFile.getName(),client);
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
return dirSize;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.