I want to display complete hierarchy of a directory at a remote location using JSch. The location has multiple folders and a folder may or may not have files.
Code written by me (taken reference from SFTP Read all files in directory):
sftpChannel.cd(remotePath);
Vector<String> files = sftpChannel.ls("*");
List<String> ret=new ArrayList<>();
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()+"file");
}
if (true && entry.getAttrs().isDir())
{
if (!entry.getFilename().equals(".") && !entry.getFilename().equals(".."))
{
ret.add(entry.getFilename()+"folder");
}
}
}
}
System.out.println(ret);
This code is only showing top-level folder names, files in those folders are not read.
I am using jsch-0.1.54.
Thanks
Just implement a recursive function that iterates into subdirectories, like:
public static void listDirectory(
ChannelSftp channelSftp, String path, List<String> list) throws SftpException
{
Vector<LsEntry> files = channelSftp.ls(path);
for (LsEntry entry : files)
{
if (!entry.getAttrs().isDir())
{
list.add(path + "/" + entry.getFilename());
}
else
{
if (!entry.getFilename().equals(".") && !entry.getFilename().equals(".."))
{
listDirectory(channelSftp, path + "/" + entry.getFilename(), list);
}
}
}
}
来源:https://stackoverflow.com/questions/49652526/list-complete-hierarchy-of-a-directories-at-sftp-server-using-jsch-in-java