Open In App

How to Get a List of Files From the SFTP Server in Java?

In this tutorial, we’ll talk about how to use Java to retrieve a list of files from an SFTP server. We will use SSHClient for creating an SFTP client. First, add a maven dependency to your project.




<dependency>
    <groupId>com.hierynomus</groupId>
    <artifactId>sshj</artifactId>
    <version>0.27.0</version>
</dependency>

To connect to the SFTP server, we use SSHClient. In addition to providing host key verification, we must also supply login credentials. SFTPClient will be created by SSHClient, and we can use that object to carry out various tasks on the SFTP server. Here, we are retrieving a list of all files from a specific server directory. The process of listing files from an SFTP server essentially involves five phases.

File: SftpListFiles.java




import java.io.*;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.RemoteResourceInfo;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
  
import java.io.IOException;
import java.util.List;
  
public class SftpListFiles {
    public static void main(String[] args) throws IOException {
        // create a instance of SSHClient
        SSHClient client = new SSHClient();
  
        // add host key verifier
        client.addHostKeyVerifier(new PromiscuousVerifier());
  
        // connect to the sftp server
        client.connect("localhost");
  
        // authenticate by username and password.
        client.authPassword("test_user", "123");
  
        // get new sftpClient.
        SFTPClient sftpClient = client.newSFTPClient();
  
        // Give the path to the directory from which
        // you want to get a list of all the files.
        String remoteDir = "/test_user/demo";
        List<RemoteResourceInfo> resourceInfoList = sftpClient.ls(remoteDir);
  
        for (RemoteResourceInfo file : resourceInfoList) {
            System.out.printf("File name is %s", file.getName());
            System.out.println("");
        }
    }
}

Output:

List files from Sftp server


Article Tags :