How to show the progress of an upload and download with JSCH (SFTP) Android

How to show the progress of an upload and download with JSCH (SFTP) 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 only can display the progress of an upload and download, with the methods put and get, we'll symply add a new class that will retrieve the progress of every process in the third parameter of those like this :

First, we need to create a class that will handle this problem for you, is so simply as :

package com.myxxxxxxpackage.something;

// Important to import the SftpProgressMonitor of JSCH
import com.jcraft.jsch.SftpProgressMonitor;

// Change the class name if you want
public class progressMonitor implements SftpProgressMonitor{
    private long max                = 0;
    private long count              = 0;
    private long percent            = 0;
    private CallbackContext callbacks = null;
    
    // If you need send something to the constructor, change this method
    public progressMonitor() {}

    public void init(int op, java.lang.String src, java.lang.String dest, long max) {
        this.max = max;
        System.out.println("starting");
        System.out.println(src); // Origin destination
        System.out.println(dest); // Destination path
        System.out.println(max); // Total filesize
    }

    public boolean count(long bytes){
        this.count += bytes;
        long percentNow = this.count*100/max;
        if(percentNow>this.percent){
            this.percent = percentNow;

            System.out.println("progress",this.percent); // Progress 0,0
            System.out.println(max); //Total ilesize
            System.out.println(this.count); // Progress in bytes from the total
        }

        return(true);
    }

    public void end(){
            System.out.println("finished");// The process is over
            System.out.println(this.percent); // Progress
            System.out.println(max); // Total filesize
            System.out.println(this.count); // Process in bytes from the total
    }
}

Then, we will use this class as a third parameter of our Put and Get functions like this :

// in the Upload 
sftp.put("mylocalfilepath.txt","myremotefilepath.txt",new progressMonitor());

// in the Download

sftp.get("remotefilepath.txt","mynewlocalfilepath.txt",new progressMonitor());

these functions can have a third parameters, which expects to be a progress monitor class that extends the sftpProgressMonitor.

You can read more about how to upload a file to a server using JSCH (sftp) here.

Become a more social person