如何使用JSch的SFTP通道获取目录和文本文件?

问题描述 投票:1回答:2

嗨,我正在开发一个连接到远程服务器并浏览不同目录的应用程序。

在这里,我想只向用户显示目录和文本文件。在JSch中使用SFTP通道,我可以执行ls方法。但是这种方法可以给我这种格式的结果"*""*.txt"。分别使用ls我可以获得目录列表和文本文件列表。由于我单独使用它,我必须使用2种不同的ls方法,如:

sftpChannel.ls("*"); 
sftpChannel.ls("*.txt");

1st给了我所有条目,我必须循环和过滤目录。第二,我得到所有文本文件。

如何使用最少的代码获取目录列表和文本文件列表。我不想循环两次。谢谢

java sftp jsch
2个回答
3
投票

使用ls("")。然后循环返回的条目,并仅选择您想要的条目。

即那些LsEntry.getFilename()".txt"LsEntry.getAttrs().isDir()结尾的人。


0
投票
We can use like this, read directories and files also.   

 public List<String> readRemoteDirectory(String location){
            System.out.println("Reading location : "+location);
            Session session = null;
            Channel channel = null;
            ChannelSftp channelSftp = null;

            List<String> filesList = new ArrayList<String>();

            String separator = getSeparator();

            try{
                JSch jsch = new JSch();
                session = jsch.getSession(remote_server_user,remote_server_ip,22);
                session.setPassword(remote_server_password);           
                java.util.Properties config = new java.util.Properties();
                config.put("StrictHostKeyChecking", "no");
                config.put("PreferredAuthentications", "publickey,keyboard-interactive,password");
                session.setConfig(config);
                session.connect();
                channel = session.openChannel("sftp");
                channel.connect();
                channelSftp = (ChannelSftp)channel;

                channelSftp.cd(location);

                Vector filelist = channelSftp.ls("*");
                for(int i=0; i<filelist.size();i++){
                    LsEntry entry = (LsEntry) filelist.get(i);  
                    if (".".equals(entry.getFilename()) || "..".equals(entry.getFilename())) {
                        continue;
                    }

                    if(entry.getAttrs().isDir()){
                        System.out.println(entry.getFilename());
                        //System.out.println("Entry"+location+separator+entry.getAttrs());
                        filesList.add(entry.getFilename());
                    }

                }



            }catch(Exception ex){
                ex.printStackTrace();
                logger.debug(ex.getMessage());
               if(ex.getMessage().equals("No such file")){
                   logger.debug("No Such File IF");
               }


            }finally{
                 channel.disconnect();
                 session.disconnect(); 
            }

            return filesList;
        }
© www.soinside.com 2019 - 2024. All rights reserved.