Learn how to download a file from your device to a remote path (sftp server) using the JSCH Library in Android (and other platforms because we are using Java)

How to download a file to a server using JSCH (SFTP) in android

Create a sftp client with Java has become really easy using JSCH Library.

JSch is a pure Java implementation of SSH2 (We can use SFTP Channel). JSch allows you to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate its functionality into your own Java programs. JSch is licensed under BSD style license.

You can use the following code to download a file from a remote to your device with java

// Remember use the required imports (the library as well) using :

import com.jcraft.jsch.*;

/// then in our function

try {
     JSch ssh = new JSch();
     Session session = ssh.getSession("username", "myip90000.ordomain.com", 22);
     // Remember that this is just for testing and we need a quick access, you can add an identity and known_hosts file to prevent
     // Man In the Middle attacks
     java.util.Properties config = new java.util.Properties();
     config.put("StrictHostKeyChecking", "no");
     Channel channel = session.openChannel("sftp");

     ChannelSftp sftp = (ChannelSftp) channel;

     // If you need to display the progress of the upload, read how to do it in the end of the article

     // use the get method , if you are using android remember to remove "file://" and use only the relative path

     Boolean success = true;

       // The file has been succesfully downloaded
} catch (JSchException e) {
} catch (SftpException e) {

This function will do the trick for you, it uses the get method. You only need to have the path of the remote file and give a new one to the local path.

Remember that as an example, this doesn't include any security. You need to add the known hosts files if your server uses one, or add an identity if your server uses a Private key for authentication.

If you need to show an download progress read this article and learn how to do it.

This code works on any platform that uses Java and JSCH Library (Android, desktop etc).

Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.