Java program for Downloading File from SFTP server

By June 29, 2010 at 4:54 am · Java/J2EE, Open Source

Most of the people face problem to download the file from the SFTP server. Everybody thinks it will be same as FTP in java but its not so. If you are using the Apache Commons.net API then you will find below classes for FTP/FTPS but there is no class available for SFTP

  • FTPClient
  • FTPSClient

Let me make you clear FTPS is not SFTP. If you want to know more about FTP/FTPS/SFTP please read my post on it at http://kodehelp.com/difference-between-ftp-sftp-ftps/

There is a seperate API called JSch. JSch is the pure implementation of SSH2. JSch allows you to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate its functionality into your own Java programs. You can download the JSCH API from here.

Please find the below sample Java program using the JSCH API for downloading the file from SFTP server.

/**
*
*/
package com.kodehelp.sftp;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

/**
* @author kodehelp
*
*/
public class SFTPinJava {

/**
*
*/
public SFTPinJava() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
String SFTPHOST = "10.20.30.40";
int    SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "/export/home/kodehelp/";

Session 	session 	= null;
Channel 	channel 	= null;
ChannelSftp channelSftp = null;

try{
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER,SFTPHOST,SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp)channel;
channelSftp.cd(SFTPWORKINGDIR);
byte[] buffer = new byte[1024];
BufferedInputStream bis = new BufferedInputStream(channelSftp.get("Test.java"));
File newFile = new File("C:/Test.java");
OutputStream os = new FileOutputStream(newFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
int readCount;
//System.out.println("Getting: " + theLine);
while( (readCount = bis.read(buffer)) > 0) {
System.out.println("Writing: " );
bos.write(buffer, 0, readCount);
}
bis.close();
bos.close();
}catch(Exception ex){
ex.printStackTrace();
}

}

}
email

DeeKay has been working in Java, JEE and opensource technology since 7 years and has same years of experience in software development. His area of interest is TDD, Scala langauge, Java, JEE techologies.

Related Posts

Popular Posts

  • http://integrationengineer.wordpress.com HJP

    Have a look at http://www.zehon.com/
    This is one that I used a few months ago when I had to do SFTP under Java 1.4.
    They support newer versions of Java, but its also nice to see they support older versions.

  • dennis

    @HJP – Thanks for pointing out another API for doing SFTP/FTP/FTPS. I will give a shot and explore the thing so that i can distribute this knowledge among my readers. Once again i would like to thanks u

  • Sandeepbhardwaj01

    Great post , i searched a lot from last two days but no suitable solution found , now i found what i am looking for.
    Great work keep it up..

  • Sandeepbhardwaj01

    Great post , i searched a lot from last two days but no suitable solution found , now i found what i am looking for.
    Great work keep it up..

  • http://vigilance.co.in Admin

    @Sandeep – I’m Glad that you liked my post. Please do visiting my blog for new post :)

  • http://vigilance.co.in Admin

    @Sandeep – I’m Glad that you liked my post. Please do visiting my blog for new post :)

  • Myextrawork

    Please give me the code to upload a file to sftp/ftp location using the above program.

  • Myextrawork

    Please give me the code to upload a file to sftp/ftp location using the above program.

  • http://vigilance.co.in Admin
  • http://vigilance.co.in Admin
  • Myextrawork

    Thanks sir… But this program doesn’t work for me when I say session.setProxy.
    Also can you please help me with JSchOverJHttpTunnel.java http://www.jcraft.com/jhttptunnel/examples/JSchOverJHttpTunnel.java … Its not working for me, its giving Connectoin timed out error.

    Thanks.

  • Myextrawork

    Thanks sir… But this program doesn’t work for me when I say session.setProxy.
    Also can you please help me with JSchOverJHttpTunnel.java http://www.jcraft.com/jhttptunnel/examples/JSchOverJHttpTunnel.java … Its not working for me, its giving Connectoin timed out error.

    Thanks.

  • Hemant

    Hi can you provide the guidance as how to read a file C:TEMPlog.txt which is on the windows server from a app server having linux environment.actually we have a code which can read the file C:TEMPlog.txt and perform some operation but it does that locally.same code we want to deploy on a app server which can read document from windows server’s C:TEMPlog.txt

    • http://kodehelp.com/ Deekay

      Is there any FTP or SFTP port opened on Windows machine ?

  • Aman

    Awesom man it is working like a charm just change the gt symbol to >

  • Saikiran

    Hi,

    I am trying to upload a file using the API

    put(String) : OutputStream.

    I am trying to get InputStream & OutputStream and trying to read chunk by chunk from InputStream and writing to OutputStream.

    But after reading two or threchunks..it throws and error and stops

    ——-

    public static void main(String[] args) {
    System.out.println(“Test”);
    SFTPUtils sftp = new SFTPUtils(“myhost”, “root”, “root”);
    OutputStream bos = null;
    InputStream is = null;
    SftpATTRS attrs1;
    try {
    System.out.println(“connectioning…. Start”);
    sftp.connect(); // this method makes connection
    bos = sftp.getOutputStream(“/test/sfsite/test3.mpg”);
    is = sftp.getInputStream(“/test/site6400ftp/358ac365-b2a5-4a7a_POSTER_1_2.jpg”);
    int filesize = 1460419;
    byte[] buffer = new byte[filesize];
    // byte[] buffer = new byte[10240];

    int readCount;
    int t_readCount = 0;
    int t_count_update = 0;

    do {
    readCount = is.read(buffer, 0, filesize);
    t_readCount+=readCount;
    System.out.println(buffer.toString());
    System.out.println(“readCount :” + readCount);
    bos.write(buffer, 0, readCount);
    } while (readCount > 0 );
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    try {
    is.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    try {
    bos.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    }

    —————–

    public static class MyProgress implements SftpProgressMonitor {

    /* (non-Javadoc)
    * @see com.jcraft.jsch.SftpProgressMonitor#count(long)
    */
    @Override
    public boolean count(long arg0) {
    System.out.println(“progress :” + arg0);
    return true;
    }

    /* (non-Javadoc)
    * @see com.jcraft.jsch.SftpProgressMonitor#end()
    */
    @Override
    public void end() {
    System.out.println(“end”);

    }

    /* (non-Javadoc)
    * @see com.jcraft.jsch.SftpProgressMonitor#init(int, java.lang.String, java.lang.String, long)
    */
    @Override
    public void init(int arg0, String arg1, String arg2, long arg3) {
    System.out.println(“size:”+arg3);

    }

    }

    output:
    ——-

    connectioning…. Start
    size:1460419
    progress :16371
    readCount :16371
    progress :16384
    readCount :16384
    The request is not in order.
    end
    java.io.IOException: error
    at com.jcraft.jsch.ChannelSftp$2.read(ChannelSftp.java:1301)
    at com.biztunnel.lib.util.file.SFTPUtils.main(SFTPUtils.java:1165)

    ———-

  • Sravy

    I used this example to download a file from sftp server in javaJSch jsch = new JSch();After this line It is giving noClassDefinitionFoundError, I did add the jsch-0.1.50.jar into my project and added it to the classpath too and it still gives me the error, is there something I am missing, Thank you

  • Leandro Fracaro

    Thank you, it have helped me, but BufferedInputStream bis = new BufferedInputStream(channelSftp.get(“server.log”));
    is returning with all the bits = 0 to me the path is right..
    :[

  • Shahina Hameed

    Thank u so much….. You saved my time.
    one suggstn pls change “>” with “>”

    • http://kodehelp.com/ Deekay

      Thanks for pointing out this typo error. I have corrected.

  • karthik

    I am able to copy the file content to the server with limitation as below
    1st line on the remote file as
    xyz.abc.com
    ssh-rsa
    AAAAB3NzaC1yc2EAAAABIwAAAQEAp8wCyUgYWpmMEau1s/G2yy8Pow8nIoB1JuG8yrlLeAUtGeMq3rODDHyyxzMhExyC7kHeTiCCal31WSF62OkZo8N/gc8Uu3p+jkpdi48M7IiXwD2NrbAQKYeQmiSSP7T1VFxMH5oxGcYzRVV6CEGTFDTrkyFXwg0fekcLrjmHN5lovTH9ptlUjks7zGFJFNMDB6r7LpUbYjx6zpbhs+/nOEn4hdlCotWjbfIM+uqRVvdfz4eGISgdmPyYYQSlwJ8W58eaAfTbEyluN3e2JNoaJ9LxC391Q/o0EA4Yx3pycsFeRIRjmJyoYOFfACRzw/zS/Bv/79ZlcRA/9tIdyl05vQ==

    Can any one help me, How to avoid this?

    Thanks in advance

    • http://kodehelp.com/ Deekay

      could you please elaborate a more on your issue ?

  • karthik

    I am able to copy the file content to the server with limitation as below
    1st line on the remote file as
    xyz.abc.com
    ssh-rsa
    AAAAB3NzaC1yc2EAAAABIwAAAQEAp8wCyUgYWpmMEau1s/G2yy8Pow8nIoB1JuG8yrlLeAUtGeMq3rODDHyyxzMhExyC7kHeTiCCal31WSF62OkZo8N/gc8Uu3p+jkpdi48M7IiXwD2NrbAQKYeQmiSSP7T1VFxMH5oxGcYzRVV6CEGTFDTrkyFXwg0fekcLrjmHN5lovTH9ptlUjks7zGFJFNMDB6r7LpUbYjx6zpbhs+/nOEn4hdlCotWjbfIM+uqRVvdfz4eGISgdmPyYYQSlwJ8W58eaAfTbEyluN3e2JNoaJ9LxC391Q/o0EA4Yx3pycsFeRIRjmJyoYOFfACRzw/zS/Bv/79ZlcRA/9tIdyl05vQ==

    Can any one help me, How to avoid this?

    Thanks in advance

  • http://vigilance.co.in admin

    You can find code for uploading a file to SFTP location at below URL

    http://vigilance.co.in/java-program-for-uploading-file-to-sftp-server/