是否有方法使用Java JSch确定Unix服务器上最新文件的名称?
我想把最新的文件从服务器复制到本地机器。我已经有了一个有用的密码。但我无法辨认最新的档案。该文件夹包含以下格式的多个文件:
Some Report dd/MM/yyyy hh:ss
我尝试了this post中提到的代码,但是它没有获取最新的文件。而且,代码似乎从未停止执行。
任何帮助都将不胜感激。
发布于 2016-11-18 06:36:23
我的解决方案基于在Finding file size and last modified of SFTP oldest file using Java中发布的代码,并做了以下修改:
nextTime
和currentOldestTime
的比较从if (nextTime < currentOldestTime)
改为if (nextTime > currentOldestTime)
。这将获得最新的文件。发布于 2019-02-13 07:21:58
下面是使用jsch将远程服务器上的最小文件复制到本地的工作程序:
package com.poc.client;
import java.util.Vector;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
public class CopyFileRemoteToLocal {
public static void main(String[] args) {
String hostname = "hostName";
String username = "userName";
String password = "password";
String copyFrom = "serverFilePath";
String copyTo = "LocalFilePath";
JSch jsch = new JSch();
Session session = null;
System.out.println("Trying to connect.....");
try {
session = jsch.getSession(username, hostname, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
Vector<LsEntry> vector = (Vector<LsEntry>) sftpChannel.ls(copyFrom);
ChannelSftp.LsEntry list = vector.get(0);
String oldestFile =list.getFilename();
SftpATTRS attrs=list.getAttrs();
int currentOldestTime =attrs.getMTime();
String nextName=null;
LsEntry lsEntry=null;
int nextTime;
for (Object sftpFile : vector) {
lsEntry = (ChannelSftp.LsEntry) sftpFile;
nextName = lsEntry.getFilename();
attrs = lsEntry.getAttrs();
nextTime = attrs.getMTime();
if (nextTime > currentOldestTime) {
oldestFile = nextName;
currentOldestTime = nextTime;
}
}
System.out.println("File name is ...."+oldestFile);
sftpChannel.get(copyFrom+oldestFile, copyTo);
sftpChannel.exit();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
System.out.println("Done !!");
}
}
发布于 2016-11-17 14:47:02
根据你提到的帖子,this post
有代码行,其中规定只筛选xml文件,您是否已将其更改为检查所有文件格式?
list = Main.chanSftp.ls("*.xml");
此外,在执行线程1分钟时还调用了睡眠方法。
Thread.sleep(60000);
因此,希望代码至少运行一分钟。
这可能会有帮助
https://stackoverflow.com/questions/40657096
复制相似问题