Java SFTP Using Jsch With Example

In this article, we will see how to use JSCH library to transfer file through SFTP protocol or SFTP file transfer from Windows machine to Linux machine in a network.

Operations

  • List all files in a directory on remote Linux machine through SFTP.
  • Transfer files from local window machine to Linux machine through SFTP.
  • Delete file/files from remote Linux machine SFTP.

Pre-Requisites

  • You must know the either the hostname or IP of the remote machine.
  • The user id used to log in must have proper rights over the folder you want to access or machine.
  • Password of the remote Linux Machine.
  • SFTP port. By default, the port will be 80.

Download Jsch Library

Implementation

Create the ChannelSftp object through which you will communicate with the remote Linux Machine connection stream.

ChannelSftp sftpClient = null;
Channel channel = null;
Session session = new Session(
                              {LinuxMachineLoginId},//String value
                              {IP or hostname of remote linux machine},//String value
                              {port of }
                              );
session.setPassword({password to the linux machine});
Properties config = new Properties();
config.put(“StrictHostKeyChecking”,”no”);
session.setConfig(config);
session.connect();
channel = session.openChannel(“sftp”);
channel.connect();
sftpClient = (ChannelSftp)channel;

You have successfully created the ChannelSftp object which is ready to be used.

Operation 1: List all files present on the remote Linux machine

Now let us proceed further with an example. You want to list all files present in the folder “/tmp/test” of the remote Linux machine. So we will use the ChannelSftp object to do it.

try
{
  .
  .
  .
  Vector<LsEntry> filesList = sftpClient.ls(“/tmp/test”);
  if(vector == null || vector.ssEmpty())
      {
            return;
      }
  for( LsEntry file : filesList )
      {
            System.out.println(file.getFileName);
      }
}
finally
{
    sftpClient.disconnect();
    channel.disconnect();
    session.disconnect();
}

With the above method, you can list all files from remote server.

Operation 2: Transfer files from local window machine to Linux machine through SFTP

Now you have a file on your local machine at “C:/test/HelloWorld.txt”. You want to transfer this file to “/tmp/test” in the remote Linux machine. With below code, you can send one or more than one files.

try
{
    .
    .
    .
    sftpClient.cd(“/tmp/test”);
    File localFile = new File(“C:/test/HelloWorld.txt”);
    sftpClient.put(localFile.getAbsolutePath(),localFile.getName());
}
finally
{
    sftpClient.disconnect();
    channel.disconnect();
    session.disconnect();
}

As you can see above first we have pointed ChannelSftp object to the location where we have to transfer file on remote Linux machine. Then created the local file object and put it to the remote location.

Operation 3: Delete file/files from remote Linux machine SFTP

The code would be same as above except few things. The current directory and parent directory both would also be listed as “.” and “..” respectively which won’t be deleted so have to put conditions to not remove them.

try
{
    .
    .
    .
    Vector<LsEntry> filesList = sftpClient.ls(“/tmp/test”);
    if(vector == null || vector.ssEmpty())
      {
                        return; 
      }
 for( LsEntry file : filesList )
    {
        if(!“.”.equals(file.getFileName()) && !”..”.equals(file.getFileName()))
        {
            sftpClient.rm(“/tmp/test/”+file.getFileName());//Have to provide full path
        }
    }
}
finally
{
                           sftpClient.disconnect();
                           channel.disconnect();
                           session.disconnect();
}

Disconnecting the connections

After you used the ChannelSftp, Session and Channel object to perform the SFTP operations you have to compulsory disconnect them.

As shown in all above examples I have disconnected the ChannelSftp, Session and Channel object. Also take care of the exceptions that can be thrown or needs to be catch by the JSCH library.

If you liked the above post, please leave your comments below.

Subscribe here to stay updated on latest posts of OracleMine.com.

Leave a Reply

Your email address will not be published. Required fields are marked *