Abs
Abs

Reputation: 478

Downloading Multiple files from FTP Server using JSCH

I want to download all the files from FTP server using JSCH.

Below is the code snippet,

        List<File> fileList = null;
        Vector<ChannelSftp.LsEntry> list = sftpChannel.ls(remoteFolder);
        for (ChannelSftp.LsEntry file : list) {

            if( getLog().isDebugEnabled() ){
                getLog().debug("Retrieved Files  from the folder  is"+file);
            }

            if (!(new File(file.getFilename())).isFile()) {
                continue;
            }
       fileList.add(new File(remoteFolder,file.getFilename())) ;
       return fileList; 

The method will return List, for another method to download the files from the remote server using sftpChannel.get(src,dest) ;

Please let me know if the code is ok. I don't have an environment to test, so can't confirm it. But somewhat similar code i wrote for FTPClient and it works.

Appreciate your help.

Upvotes: 1

Views: 3009

Answers (1)

Tushar Mishra
Tushar Mishra

Reputation: 1400

You can use SftpATTRS to get the file information. You can declare a wrapper class to store file information. An example shown below.

    private class SFTPFile
{
    private SftpATTRS sftpAttributes;

    public SFTPFile(LsEntry lsEntry)
    {
        this.sftpAttributes = lsEntry.getAttrs();
    }

    public boolean isFile()
    {
        return (!sftpAttributes.isDir() && !sftpAttributes.isLink());
    }
}

Now you can use this class to test if the LsEntry is a file

    private List<SFTPFile> getFiles(String path)
{
    List<SFTPFile> files = null;
    try
    {
        List<?> lsEntries = sftpChannel.ls(path);
        if (lsEntries != null)
        {
            files = new ArrayList<SFTPFile>();
            for (int i = 0; i < lsEntries.size(); i++)
            {
                Object next = lsEntries.get(i);
                if (!(next instanceof LsEntry))
                {
                    // throw exception
                }
                SFTPFile sftpFile = new SFTPFile((LsEntry) next);
                if (sftpFile.isFile())
                {
                    files.add(sftpFile);
                }
            }
        }
    }
    catch (SftpException sftpException)
    {
        //
    }
    return files;
}

Now you can use sftpChannel.get(src,dest) ; to download files.

Upvotes: 0

Related Questions