Java - Connecting to SFTP, Uploading & Downloading Files

SFTP (SSH File Transfer Protocol; also known as Secure File Transfer Protocol) is a protocol packaged with SSH for transferring files between computers. Because of its security, SFTP is often preferable to FTP, and therefore many systems have been migrating from FTP to SFTP. Sometimes the process of uploading or downloading files needs to be handled by the back end of an application. In this tutorial, I'm going to show you how to connect to an SFTP server with Java, including how to get authenticated as well as how to upload and download a file.

Dependencies

We're going to use com.jcraft.jsch as the library for connecting to SFTP server. Add it to the dependencies of your project. Below are the example if you use maven and gradle. Just adjust it yourself if you're using other dependency manager.

pom.xml

  <!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
  <dependency>
	    <groupId>com.jcraft</groupId>
	    <artifactId>jsch</artifactId>
	    <version>0.1.55</version>
  </dependency>

 

build.gradle

  compile 'com.jcraft:jsch:0.1.55'

Connecting to SFTP Server

To make to code reusable and more readable, it's better to create a helper class which includes the methods for connecting to SFTP server as well as uploading and downloading files.

For connecting to an SFTP server, first create an instance of JSch. If you need to provide certificate for authentication, you can use addIdentity. Then create a session of the JSch sesion using jsch.getSession. If the server requires password, we can use setPassword and modify the way we use jsch.getSession, as exemplified below.

  package com.woolha.example.helpers;

  public class SFTPClient {

      private String host = "ftp.example.com"
      private int port = 22;
      private Session session = null;

      public SFTPClient() {

      }

      public void connect() throws JSchException {
          JSch jsch = new JSch();

          // Uncomment the line below if the FTP server requires certificate
          // jsch.addIdentity("private-key-path);
  
          session = jsch.getSession(server);

          // Comment the line above and uncomment the two lines below if the FTP server requires password
          // session = jsch.getSession("username", host, port);
          // session.setPassword("the-password");

          session.setConfig("StrictHostKeyChecking", "no");
          session.connect();
      }
  }

Uploading File

Having connected and authenticated to the SFTP server, we can upload a file by creating a new ChannelSftp and use its put method. The first argument is the path of the local file, while the second argument is the destination path in the SFTP server.

  public void upload(String source, String destination) throws JSchException, SftpException {
      Channel channel = session.openChannel("sftp");
      channel.connect();
      ChannelSftp sftpChannel = (ChannelSftp) channel;
      sftpChannel.put(source, destination);
      sftpChannel.exit();
  }

Downloading File

To download a file, we also need to create a new ChannelSftp. Then, use get method with the first argument is the path of the file in SFTP server and the second argument is the local path where the file be downloaded.

  public void download(String source, String destination) throws JSchException, SftpException {
      Channel channel = session.openChannel("sftp");
      channel.connect();
      ChannelSftp sftpChannel = (ChannelSftp) channel;
      sftpChannel.get(source, destination);
      sftpChannel.exit();
  }

Disconnecting from server

After we have done the operations, we need to cut the connection to the server.

  public void disconnect() {
      if (session != null) {
          session.disconnect();
      }
  }

Full Code

Below is the full code of the helper.

  package com.woolha.example.helper;
  
  import com.jcraft.jsch.*;

  public class SFTPClient {
  
      private Session session = null;
  
      @Value("${private-key-path}")
      private String privateKeyPath;
  
      public void connect() throws JSchException {
          JSch jsch = new JSch();

          // Uncomment the line below if the FTP server requires certificate
          jsch.addIdentity("private-key-path);
  
          session = jsch.getSession(server);

          // Uncomment the two lines below if the FTP server requires password
          session = jsch.getSession("username", host, port);
          session.setPassword("the-password");

          session.setConfig("StrictHostKeyChecking", "no");
          session.connect();
      }
  
      public void upload(String source, String destination) throws JSchException, SftpException {
          Channel channel = session.openChannel("sftp");
          channel.connect();
          ChannelSftp sftpChannel = (ChannelSftp) channel;
          sftpChannel.put(source, destination);
          sftpChannel.exit();
      }
  
      public void download(String source, String destination) throws JSchException, SftpException {
          Channel channel = session.openChannel("sftp");
          channel.connect();
          ChannelSftp sftpChannel = (ChannelSftp) channel;
          sftpChannel.get(source, destination);
          sftpChannel.exit();
      }
  
      public void disconnect() {
          if (session != null) {
              session.disconnect();
          }
      }
  }

Upload Example

  SFTPClient sftpClient = new SFTPClient();

  sftpClient.connect();
  sftpClient.upload("images/img1.avif", "images/img1_server.avif");
  sftpClient.disconnect();

Download Example

  SFTPClient sftpClient = new SFTPClient();

  sftpClient.connect();
  sftpClient.download("images/img1_server.avif", "images/img1_downloaded.avif", );
  sftpClient.disconnect();