Sample code for 30+ languages & platforms
Java

SFTP Upload and Download to a StringBuilder Object

See more SFTP Examples

Demonstrates how to SFTP upload from a Chilkat StringBuilder object, and download into a StringBuilder object.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.SFtp;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example requires the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        SFtp sftp = new SFtp();

        // Set some timeouts, in milliseconds:
        sftp.setConnectTimeoutMs(5000);
        sftp.setIdleTimeoutMs(10000);

        // Connect to the SSH server and then authenticate.
        int port = 22;
        try {
            sftp.connect("MY-SSH-SERVER-DOMAIN-OR-IP", port);
            sftp.authenticatePw("MY-SSH-LOGIN", "MY-SSH-PASSWORD");
            sftp.initializeSftp();
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        StringBuilder sbA = new StringBuilder();
        sbA.loadFile("qa_data/hamlet.xml", "utf-8");

        // Upload the contents of sbA to the SSH/SFTP server.
        boolean bIncludeBOM = false;
        String remotePath = "sftpTesting/hamlet.xml";
        try {
            sftp.uploadSb(sbA, remotePath, "utf-8", bIncludeBOM);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Download the file..
        StringBuilder sbB = new StringBuilder();
        try {
            sftp.downloadSb(remotePath, "utf-8", sbB);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Verify that sbA and sbB have the exact same contents.
        System.out.println("size of sbA: " + sbA.getLength());
        boolean bCaseSensitive = true;
        if (sbA.contentsEqualSb(sbB, bCaseSensitive)) {
            System.out.println("Contents are equal. Success.");
        } else {
            System.out.println("Contents are NOT equal.  Failed.");
        }

        sftp.disconnect();
    }
}