【问题标题】:List complete hierarchy of a directories at SFTP server using JSch in Java使用 Java 中的 JSch 列出 SFTP 服务器上目录的完整层次结构
【发布时间】:2018-09-14 02:31:30
【问题描述】:

我想使用 JSch 在远程位置显示目录的完整层次结构。该位置有多个文件夹,一个文件夹可能有也可能没有文件。

我写的代码(参考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);

此代码仅显示顶级文件夹名称,不会读取这些文件夹中的文件。

我正在使用 jsch-0.1.54。

谢谢

【问题讨论】:

    标签: java ssh sftp jsch


    【解决方案1】:

    只需实现一个迭代到子目录的递归函数,例如:

    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);
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      • 1970-01-01
      • 2020-01-28
      • 2010-10-14
      相关资源
      最近更新 更多