Jsch is an SSH implementation API and in this tutorial we will see how to create an sftp connection to an ftp server.

One of the most crucial parts of sftp client server communication, is private-public key ( certificate ) matching. Our client can be easily aware of the certificate existance via '.setKnownHosts( )' function, provided by JSCH API.

Moreover,we have to configure the authentication of the client.In our example we will use password authentication.

As a final step the sftp client will connect to the ftp server by opening an sftp channel.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.HostKey;
import com.jcraft.jsch.HostKeyRepository;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class JschManager {
	public static void main(String[] args) {
		java.security.Security.insertProviderAt( new org.bouncycastle.jce.provider.BouncyCastleProvider(), 1 );
		
		
		 JSch jsch = new JSch();
	        Session session = null;
	        try {
			//open session
	            session = jsch.getSession("username", "127.0.0.1", 22);

	           //set ftp server's certificate
	            jsch.setKnownHosts("path\\to\\certificate.crt");
	            
	            
	            //configure authentication
	            session.setConfig("PreferredAuthentications", "password");
	            session.setPassword("password");

	            session.connect();
				//open sftp channel
	            Channel channel = session.openChannel("sftp");
	            channel.connect();
	            ChannelSftp sftpChannel = (ChannelSftp) channel;
	            sftpChannel.get("file.txt", "localFile.txt");
	            sftpChannel.exit();
	            session.disconnect();
	        } catch (JSchException e) {
	            e.printStackTrace();
	        }
	        catch (SftpException e) {
	            e.printStackTrace();
	        }
	}
	
	
}