mona mona - 1 year ago 190
Java Question

Retrieving data from an SFTP server using JSch

I am using JSch for retrieving a file from a remote machine by SFTP. Here is the code

public class TestSFTPinJava {

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

Channel channel = session.openChannel("sftp");
ChannelSftp sftpChannel = (ChannelSftp) channel;
System.out.println("Directory:" + sftpChannel.pwd());"remoteDirectory/");
System.out.println("Directory after cd:" + sftpChannel.pwd());

} catch (JSchException e) {
} catch (SftpException e) {

Now, I have two questions:

  • sftpChannel.get("remote-data.txt");
    throws an exception:

    no such file

    at com.jcraft.jsch.ChannelSftp.throwStatusError(

    at com.jcraft.jsch.ChannelSftp._stat(

    at com.jcraft.jsch.ChannelSftp.get(

    at com.jcraft.jsch.ChannelSftp.get(

    at TestSFTPinJava.main(

  • I am not sure how to specify the location in my local system where the file will be saved.
    does not look right to me.

Please help with suggestions, Thanks!

Answer Source

Concerning your point 1, I suspect that the default directory after connecting is not what you expect. Try using an absolute remote path. Does sftpChannel.pwd() return the directory the file remote-data.txt is in on the remote machine ?

Concerning your point 2, looking at one sees that there is the following method in ChannelSftp:

 public void put(String src, String dst)

which indeed has a source and destination file name argument.

I guess you had already a look the Jsch sftp example at ?