简体   繁体   中英

SFTP Read all files in directory

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM