List complete hierarchy of a directories at SFTP server using JSch in Java

折月煮酒 提交于 2019-12-23 00:52:26

问题


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


回答1:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!