Sample code for 30+ languages & platforms
Java

Get the Byte Count of the Last SFTP Read

See more SFTP Examples

Demonstrates the Chilkat SFtp.LastReadNumBytes method, which returns the number of bytes received by the most recent read for a handle. The only argument is the handle.

Background: SFTP reads may return fewer bytes than requested even before the end of the file, so knowing the actual count is useful for tracking progress and for advancing an explicit offset by the right amount. Both a normal EOF read and a failed read report 0, so pair this with Eof and LastReadFailed to interpret a zero-byte result correctly.

Chilkat Java Downloads

Java
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    //  Demonstrates the SFtp.LastReadNumBytes method, which returns the number of bytes received by
    //  the most recent read for a handle.  The only argument is the handle.

    CkSFtp sftp = new CkSFtp();

    //  Connect, authenticate, and initialize the SFTP subsystem.
    int port = 22;
    success = sftp.Connect("sftp.example.com",port);
    if (success == false) {
        System.out.println(sftp.lastErrorText());
        return;
        }

    //  Normally you would not hard-code the password in source.  You should instead obtain it
    //  from an interactive prompt, environment variable, or a secrets vault.
    String password = "mySshPassword";

    success = sftp.AuthenticatePw("mySshLogin",password);
    if (success == false) {
        System.out.println(sftp.lastErrorText());
        return;
        }

    success = sftp.InitializeSftp();
    if (success == false) {
        System.out.println(sftp.lastErrorText());
        return;
        }

    String handle = sftp.openFile("subdir/data.txt","readOnly","openExisting");
    if (sftp.get_LastMethodSuccess() == false) {
        System.out.println(sftp.lastErrorText());
        return;
        }

    CkBinData bd = new CkBinData();
    int chunkSize = 4096;
    boolean reading = true;
    while (reading) {
        success = sftp.ReadFileBd(handle,chunkSize,bd);
        if (sftp.LastReadFailed(handle)) {
            System.out.println(sftp.lastErrorText());
            return;
            }

        //  Report how many bytes the last read actually returned.  A normal EOF read reports 0.
        int lastCount = sftp.LastReadNumBytes(handle);
        System.out.println("Last read returned " + lastCount + " bytes.");

        reading = !sftp.Eof(handle);
        }

    success = sftp.CloseHandle(handle);
    if (success == false) {
        System.out.println(sftp.lastErrorText());
        return;
        }

    System.out.println("Total: " + bd.get_NumBytes() + " bytes.");

    sftp.Disconnect();
  }
}