问题
I have created a successful connection using SFTP com.jcraft.jsch
I also created a directory folder under HostDir
like: channelSftp.mkdir("sftp.test");
Now i want to read all file/folder names under host directory, I do not see any appropriate method or example.
thanks
回答1:
Done it using this ..
ChannelSftp sftp = (ChannelSftp) channel;
sftp.cd(hostDir);
Vector<String> files = sftp.ls("*");
for (int i = 0; i < files.size(); i++)
{
Object obj = files.elementAt(i);
if (obj instanceof com.jcraft.jsch.ChannelSftp.LsEntry)
{
LsEntry entry = (LsEntry) obj;
if (true && !entry.getAttrs().isDir())
{
ret.add(entry.getFilename());
}
if (true && entry.getAttrs().isDir())
{
if (!entry.getFilename().equals(".") && !entry.getFilename().equals(".."))
{
ret.add(entry.getFilename());
}
}
}
}
System.out.println(ret);
回答2:
While the accepted answer works, the code is overcomplicated and has a number of issues, the main one being the cast from String
to LsEntry
.
This is a simpler solution without obscure casts:
List<String> list = new ArrayList<>();
ChannelSftp sftp = (ChannelSftp) channel;
Vector<LsEntry> files = sftp.ls(path);
for (LsEntry entry : files)
{
if (!entry.getFilename().equals(".") && !entry.getFilename().equals(".."))
{
list.add(entry.getFilename());
}
}
System.out.println(list);
If you want to list the files recursively (including files in subdirectories), see:
List complete hierarchy of a directories at SFTP server using JSch in Java
来源:https://stackoverflow.com/questions/24625182/sftp-read-all-files-in-directory