SFTP Read all files in directory

孤人 提交于 2019-12-04 11:46:54

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

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

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