How to connect to SFTP server using java

Introduction:

SFTP stands for Secure File Transfer Protocol. used for transferring large files over the web. It provides the highest level of protection.

we can transfer files through SFTP using JSch library in java. JSch stands for Java Secure Shell. we can find as maven and gradle dependency. JSch is a pure java implementation of SSH2 protocol. With the help of JSch library we can copy files from local machine to remote server without any manual interventions.

JSch Maven Dependency:

Need to add below dependency in pom.xml file. then do maven install. dependency will get download by the maven repository.

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>

To connect to SFTP server. first we need to initialize JSch object.

JSch ssh = new JSch();

Any connection between the client and server requires a session. and the session will get instantiated using JSch object.

Session session = ssh.getSession(login, hostname, 22);
session.setPassword(password);
session.connect();
  • login is the username of the SFTP server.
  • hostname is the ip address of the server.
  • 22 is the bydefault SFTP protocol port.
  • password is the SFTP server's password.

Before connecting to SFTP server we need to provide secure validation to configure the current session.

java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);

Now from this session object we can create a channel to manipulate files over the SFTP server

ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp");
sftp.connect();

by default when opening ChannelSftp Present working directory will be root or user.

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

    public static void main(String[] args) {
        try{
           String hostname = "127.0.0.1";
           String login = "admin";
           String password = "admin";

           java.util.Properties config = new java.util.Properties();
           config.put("StrictHostKeyChecking", "no");

           JSch ssh = new JSch();
           Session session = ssh.getSession(login, hostname, 22);
           session.setConfig(config);
           session.setPassword(password);
           session.connect();

           ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp");
           sftp.connect();
           sftp.disconnect();
           session.disconnect();
       }catch(Exception e){
            e.printStackTrace();
       }
    }

java will catch the JSchException and SftpException if any connection issues raised.