How to get list of Files from SFTP Server in Java?

DeeKay April 29, 2011 at 3:25 pm · How To, SFTP

To get list of files from SFTP server you have to use JSCH API. For more details on how to use JSCH API please refer to by previous post Java program for Downloading File from SFTP server.

Below Java code show how to get the list of files from SFTP server.


package com.kodehelp.sftp;

import java.nio.channels.Channel;
import java.util.Vector;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

/**
 * @author https://kodehelp.com
 *
 */
public class SFTPinJava {

    /**
     * @param args
     */
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        String SFTPHOST = "10.20.30.40";
        int SFTPPORT = 22;
        String SFTPUSER = "USERNAME";
        String SFTPPASS = "PASSWORD";
        String SFTPWORKINGDIR = "/export/home/kodehelp/";

        Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;

        try {
            JSch jsch = new JSch();
            session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
            session.setPassword(SFTPPASS);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp) channel;
            channelSftp.cd(SFTPWORKINGDIR);
            Vector filelist = channelSftp.ls(SFTPWORKINGDIR);
            for (int i = 0; i < filelist.size(); i++) {
                System.out.println(filelist.get(i).toString());
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}