SFTP Read all files in directory

a 夏天 提交于 2019-12-12 08:56:08

问题


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

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