Java program for Downloading File from SFTP server

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

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

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 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() {

	 * @param args
	public static void main(String[] args) {
		String SFTPHOST = "";
		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);
			java.util.Properties config = new java.util.Properties();
			config.put("StrictHostKeyChecking", "no");
			channel = session.openChannel("sftp");
			channelSftp = (ChannelSftp) channel;;
			byte[] buffer = new byte[1024];
			BufferedInputStream bis = new BufferedInputStream(channelSftp.get(""));
			File newFile = new File("C:/");
			OutputStream os = new FileOutputStream(newFile);
			BufferedOutputStream bos = new BufferedOutputStream(os);
			int readCount;
			while ((readCount = > 0) {
				System.out.println("Writing: ");
				bos.write(buffer, 0, readCount);
		} catch (Exception ex) {