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

	}

}