Java program for Downloading File from SFTP server

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 separate 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.

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() {
		super();
	}

	/**
	 * @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;
			while ((readCount = bis.read(buffer)) > 0) {
				System.out.println("Writing: ");
				bos.write(buffer, 0, readCount);
			}
			bis.close();
			bos.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

}

40 comments

  1. HJP says:

    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.

  2. dennis says:

    @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

  3. Sandeepbhardwaj01 says:

    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..

  4. Sandeepbhardwaj01 says:

    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..

  5. Admin says:

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

  6. Admin says:

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

  7. Myextrawork says:

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

  8. Myextrawork says:

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

  9. Myextrawork says:

    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.

  10. Myextrawork says:

    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.

  11. Hemant says:

    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

    • Deekay says:

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

  12. Aman says:

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

  13. Saikiran says:

    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)

    ———-

  14. Sravy says:

    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

  15. Leandro Fracaro says:

    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..
    :[

  16. Shahina Hameed says:

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

    • Deekay says:

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

  17. karthik says:

    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

    • Deekay says:

      could you please elaborate a more on your issue ?

  18. karthik says:

    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

  19. Khazamonod says:

    Holy indentation batman!

  20. arpit says:

    SSHHostKey how to used in this code …

  21. arpit says:

    how to used automated sftp file transfer in java?

  22. arpit says:

    please provide me some idea i doing this first time

    • Deekay says:

      @disqus_WYeguuB6zj:disqus – I didn’t understood your question completely. Are you asking how can you automate the SFTP transfer without using password ?

      Can you elaborate more ?

      • arpit says:

        thanks for reply.i want upload a file from my system to sftp remote location and download a file from sftp remote server to my local system and this process happened is repeated every 15 minute. I have to automate the download and upload automatic every 15 minutes.

        I have following details:
        FTP URL
        FTP Login

        FTP
        Pasword

        SSHHostKey

        PortNumber

        Please Helping out.
        thanks
        Arpit Mehta

  23. Robert says:

    Thank you so much, now I understand how sftp works, I was so desperate, but you saved me, good job 🙂

  24. Rinjin Lama says:

    Hi,
    Thanks for providing a code to connect with sftp. I was able to get a file, but how to get a folder from SFTP?

  25. arpit says:

    HOW TO DOWNLOAD LATEST FILE FROM SFTP SERVER FROM EVERY 15 MINUTE HOW USING FOLOOWING CODE..

  26. arpit says:

    i dont know sftp downlaod filename

  27. arpit says:

    please helping out.. thanks

  28. Niv says:

    I am getting Authentication error even when i have entered correct credentials.I am able to login to putty.

    This is the error which i am getting.Its not able to connect to the server .

    com.jcraft.jsch.JSchException: Auth fail

    at com.jcraft.jsch.Session.connect(Session.java:512)

    at com.jcraft.jsch.Session.connect(Session.java:183)

    at com.kodehelp.sftp.JSch_SFTPinJava.main(JSch_SFTPinJava.java:49)

  29. Latha Patil says:

    It is taking more than a hour to donwnload a file of size 300 MB. May not be good choice for large files.

  30. prashant says:

    How to test this code?

  31. Kumar says:

    HI,
    I have a problem. In our company we on network. I want upload the files to apatch server using ftp and ssh keys from local machine. Can you please help in this. Thanks in advance

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.