How to Read SFTP files in Java

  • Post last modified:January 21, 2023
  • Reading time:4 mins read

Using Jsch library to fetch remote files

Introduction

  • SFTP is very common way to transfer the file from one server to another.
  • Often as a client we recieve SFTP server endpoint to pull the file to our system from other system.
  • In this article we will use Java client to read the remote file which is located on SFTP server.

Note: We are using username and password in this article, but in future article we will use public , private key pair to connect.

SFTP Server

  • If you dont have SFTP server then you can setup one on local system or Cloud environment for test purpose.
  • I have setup one for my use case on GCP. My Linux environment is based on Ubuntu and I followed this guide to setup SFTP server.

Business Logic

JSch Library

  • JSch library is java implementation of SSH2. We can use to connect and operate on SFTP server using username / password , also with SSH key over secure channel.
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.55</version>
        </dependency>

Session Instance

  • At first we will create session , here we are not doing strict host checking , what that essentially means is that we are not looking the key to be added to “~/.ssh/known_hosts” file. In typical production environment we would expect the host to be add to this file.
  • We are using Username & Password method to login to SFTP server using SFTP user , but in other article we will cover using private key & public key combination.
private static Session getSession() throws JSchException {
        JSch jsch = new JSch();
        Session session = jsch.getSession(username, remoteHost);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.setPassword("sftp12345");
        session.connect();
        return session;
    }

Connect to SFTP with Session

  • Once Session is established , we can open sftp channel and connect to it.
private static ChannelSftp connect() throws JSchException {
        session = getSession();
        ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect();
        return channel;
    }

Read File Contents 

  • By this time we have access to SFTP user home directory. Here we are reading touch.txt file.
private static Stream<String> getContents(ChannelSftp channel) throws SftpException {
        InputStream inputStream = channel.get("/sftp_user/touch.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        return reader.lines();
    }

Disconnecting SFTP Channel & Session

  • Once we finish reading the file we can exit the sftp channle and disconnet the session
private static void disconnect(ChannelSftp channel) {
    channel.exit();
    session.disconnect();
}

Client Code

  • Below is our entire client code to open the channel , read the file and disconnect it.
public static void main(String[] args) throws JSchException, SftpException {
        ChannelSftp channel = connect();
        Stream<String> contents = getContents(channel);
        contents.forEach(a-> System.out.println(a));
        disconnect(channel);
    }

Entire Logic

  • Below is Class that contains enire logic.
import com.jcraft.jsch.*;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.stream.Stream;

public class SFTPClientWithUSRPWD {

    private static String remoteHost = "34.125.22.200";
    private static String username = "sftp_user";

    private static Session session = null;

    public static void main(String[] args) throws JSchException, SftpException {
        ChannelSftp channel = connect();
        Stream<String> contents = getContents(channel);
        contents.forEach(a-> System.out.println(a));
        disconnect(channel);
    }

    private static Stream<String> getContents(ChannelSftp channel) throws SftpException {
        InputStream inputStream = channel.get("/sftp_user/touch.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        return reader.lines();
    }

    private static void disconnect(ChannelSftp channel) {
        channel.exit();
        session.disconnect();
    }

    private static ChannelSftp connect() throws JSchException {
        session = getSession();
        ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect();
        return channel;
    }

    private static Session getSession() throws JSchException {
        JSch jsch = new JSch();
        Session session = jsch.getSession(username, remoteHost);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.setPassword("sftp12345");
        session.connect();
        return session;
    }
}

Result

  • I downloaded the file through the command line to check the content of the file touch.txt.
  • Its just print “success” .
  • Here is the result of the Java application execution.

Conclusion

  • In this article we used Jsch library to connect and read the file on SFTP server using username and password.
  • In future article i will cover how we can connect to sftp server using public private key.

Leave a Reply