Tuesday 4 April 2017

How to fetch or download the Files from SFTP using Java



WHAT IS SFTP?


FTP, or "File Transfer Protocol" is a popular method of transferring files between two remote systems.
SFTP, which stands for SSH File Transfer Protocol, or Secure File Transfer Protocol, is a separate protocol packaged with SSH that works in a similar way over a secure connection. The advantage is the ability to leverage a secure connection to transfer files and traverse the filesystem on both the local and remote system.
In almost all cases, SFTP is preferable to FTP because of its underlying security features and ability to piggy-back on an SSH connection. FTP is an insecure protocol that should only be used in limited cases or on networks you trust.
Although SFTP is integrated into many graphical tools, this guide will demonstrate how to use it through its interactive command line interface.
In this post we are going to see how to fetch files from SFTP using Java.
Java Code to fetch Files from SFTP:
           JSch jsch = new JSch();
           String remoteFilePath = "uo1/test";
            jsch.setKnownHosts(remoteFilePath);
           Session session = jsch.getSession("sftpUserName", "localhost");
            session.setPassword("sftpPassWord");
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
           ChannelSftp sftpChannel = (ChannelSftp) channel;
            Vector<ChannelSftp.LsEntry> list = sftpChannel.ls(remoteFilePath)
             int count = 0;
             sftpChannel.cd(remoteFilePath);
            for (ChannelSftp.LsEntry entry : list) {
             if (!entry.getAttrs().isDir()) {
                    sftpChannel.get(entry.getFilename(), entry.getFilename());
                    count++;
                }
                System.out.println(entry.getFilename());
            }
             System.out.println();
            System.out.println(count + " files downloaded.");
           sftpChannel.exit();
            session.disconnect();



No comments:

Post a Comment