Java SFTP Transfer Library

The exit() and the disconnect() must be placed in a finally block. In this example we've got a never ending program in case of an exception because a second thread won't terminate.


Here is the complete source code of an example using JSch without having to worry about the ssh key checking.

import com.jcraft.jsch.*;

public class TestJSch {
    public static void main(String args[]) {
        JSch jsch = new JSch();
        Session session = null;
        try {
            session = jsch.getSession("username", "127.0.0.1", 22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword("password");
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp) channel;
            sftpChannel.get("remotefile.txt", "localfile.txt");
            sftpChannel.exit();
            session.disconnect();
        } catch (JSchException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }
}

Edit : I'm going to keep my previous answer, as JSch is still used in many places, but if you need a better-documented library, you can use sshj. An example in how to use it to do sftp is :

SSHClient ssh = new SSHClient();
ssh.loadKnownHosts();
ssh.connect("host");
try {
    ssh.authPassword("username", "password");
    SFTPClient sftp = ssh.newSFTPClient();
    try {
        sftp.put(new FileSystemFile("/path/of/local/file"), "/path/of/ftp/file");
    } finally {
        sftp.close();
    }
} finally {
    ssh.disconnect();
}

Using JSch (a java ssh lib, used by Ant for example), you could do something like that :

Session session = null;
Channel channel = null;
try {
    JSch ssh = new JSch();
    ssh.setKnownHosts("/path/of/known_hosts/file");
    session = ssh.getSession("username", "host", 22);
    session.setPassword("password");
    session.connect();
    channel = session.openChannel("sftp");
    channel.connect();
    ChannelSftp sftp = (ChannelSftp) channel;
    sftp.put("/path/of/local/file", "/path/of/ftp/file");
} catch (JSchException e) {
    e.printStackTrace();
} catch (SftpException e) {
    e.printStackTrace();
} finally {
    if (channel != null) {
        channel.disconnect();
    }
    if (session != null) {
        session.disconnect();
    }
}

You can use JSch directly this way, or through Commons VFS, but then you'll have to have both commons vfs jar and jsch jar.

Tags:

Java

Sftp

Ssh