SFTP file transfer using Java JSch

MAHI picture MAHI · Feb 27, 2013 · Viewed 122.9k times · Source

Here is my code, which retrieves content of the file, on the remote server and display as output.

package sshexample;

import com.jcraft.jsch.*;
import java.io.*;

public class SSHexample 
{
public static void main(String[] args) 
{
    String user = "user";
    String password = "password";
    String host = "192.168.100.103";
    int port=22;

    String remoteFile="sample.txt";

    try
    {
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        System.out.println("Establishing Connection...");
        session.connect();
        System.out.println("Connection established.");
        System.out.println("Creating SFTP Channel.");
        ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
        sftpChannel.connect();
        System.out.println("SFTP Channel created.");
        InputStream out= null;
        out= sftpChannel.get(remoteFile);
        BufferedReader br = new BufferedReader(new InputStreamReader(out));
        String line;
        while ((line = br.readLine()) != null) 
        {
            System.out.println(line);
        }
        br.close();
        sftpChannel.disconnect();
        session.disconnect();
    }
    catch(JSchException | SftpException | IOException e)
    {
        System.out.println(e);
    }
}
}

Now how to implement this program that the file is copied in the localhost and how to copy a file from localhost to the server.

Here how to make work the transfer of files for any format of files.

Answer

Martin Prikryl picture Martin Prikryl · Nov 3, 2017

The most trivial way to upload a file over SFTP with JSch is:

JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();

ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();

sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");

Similarly for a download:

sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");

You may need to deal with UnknownHostKey exception.