使用JSch ChannelSftp:如何读取具有动态名称的多个文件? [英] Using JSch ChannelSftp: How to read multiple files with dynamic names?
问题描述
我必须从SFTP服务器读取一堆带有动态文件名的.CSV文件.这些文件每15分钟生成一次.
I have to read a bunch of .CSV files with dynamic file names from a SFTP server. These files get generated every 15 minutes.
我正在使用JSch的ChannelSftp,但是没有方法可以提供确切的文件名.我只看到一个.ls()
方法.这给出了一个向量,例如
I am using JSch's ChannelSftp, but there is no method which would give the exact filenames. I only see an .ls()
method. This gives a Vector e.g.
[drwxr-xr-x 2 2019 2019 144 Aug 9 22:29 .,
drwx------ 6 2019 2019 176 Aug 27 2009 ..,
-rw-r--r-- 1 2019 2019 121 Aug 9 21:03 data_task1_2011_TEST.csv,
-rw-r--r-- 1 2019 2019 121 Aug 9 20:57 data_task1_20110809210007.csv]
是否有一种简单的方法来读取目录中的所有文件并将它们复制到另一个位置?
Is there a simple way to read all the files in a directory and copy them to another location?
此代码可用于复制单个文件:
This code works for copying a single file:
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER,SFTPHOST,SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp)channel;
channelSftp.cd(SFTPWORKINGDIR);
channelSftp.get("data_task1_20110809210007.csv","data_task1_20110809210007.csv");
推荐答案
LsEntry 对象,您可以询问每个对象的名称.
The ls
method is the one you need. It returns a vector of LsEntry objects, each of which you can ask about its name.
因此,在channelSftp.cd(SFTPWORKINGDIR);
之后,您可以执行以下操作:
So, after your channelSftp.cd(SFTPWORKINGDIR);
, you could do the following:
Vector<ChannelSftp.LsEntry> list = channelSftp.ls("*.cvs");
for(ChannelSftp.LsEntry entry : list) {
channelSftp.get(entry.getFilename(), destinationPath + entry.getFilename());
}
(这假定destinationPath
是以/
(在Windows中为\
)结尾的本地目录名称.)
(This assumes destinationPath
is a local directory name ending with /
(or \
in Windows).)
当然,如果您不想在15分钟后再次下载相同的文件,则可能需要一个本地文件列表,以进行比较(使用HashSet或类似文件),或者从本地文件中删除它们.服务器.
Of course, if you don't want to download the same files again after 15 minutes, you might want to have a list of the local files, to compare them (use a HashSet or similar), or delete them from the server.
这篇关于使用JSch ChannelSftp:如何读取具有动态名称的多个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!