【问题标题】:Downloading Multiple files from FTP Server using JSCH使用 JSCH 从 FTP 服务器下载多个文件
【发布时间】:2013-02-19 18:48:26
【问题描述】:

我想使用 JSCH 从 FTP 服务器下载所有文件。

下面是代码sn-p,

        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; 

该方法将返回 List,用于另一种使用 sftpChannel.get(src,dest) 从远程服务器下载文件的方法;

请让我知道代码是否正常。 我没有环境可以测试,所以无法确认。 但是我为 FTPClient 编写的代码有些相似,并且可以正常工作。

感谢您的帮助。

【问题讨论】:

  • 这行得通。但是为什么你将 List 声明为 null 而不是由 ArrayList 实例化?
  • 是什么阻止您设置本地 SFTP 服务器?
  • isDir() 的更短的方法可能是: public boolean isDir(SftpChannel sftpChannel, String path) throws SftpException { boolean result = false;结果 = sftpChannel.lstat(path).isDir();返回结果; }

标签: sftp jsch


【解决方案1】:

您可以使用 SftpATTRS 获取文件信息。您可以声明一个包装类来存储文件信息。下面是一个例子。

    private class SFTPFile
{
    private SftpATTRS sftpAttributes;

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

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

现在你可以使用这个类来测试 LsEntry 是否是一个文件

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

现在你可以使用 sftpChannel.get(src,dest) ;下载文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    相关资源
    最近更新 更多