Wednesday, August 22, 2012

How to get SFTP connection using java code ?

Download "jsch-0.1.48.jar" and add this jar file to the project library.


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

public class SFTPConnectionTest {
public static void main(String[] args) {
JSch jsch = null;
Session session = null;
Channel channel = null;
ChannelSftp c = null;
String host = "HostName/IP";
String port = "22";
String username = "USER_NAME";
String pass = "PASSWORD";
String khfile = null;
try {
jsch = new JSch();
session = jsch.getSession(username, host, Integer.parseInt(port));
if(khfile != null)
jsch.setKnownHosts(khfile);
else
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(pass);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
c = (ChannelSftp) channel;
System.out.println("Connected sucessfully.... !!!");
                        c.put("SourceFilePATH", "DestinationFilePATH");


} catch (JSchException e) {
System.out.println("Exception occured while getting SFTP connection  :"+ e.getMessage());
} finally {
c.disconnect();
session.disconnect();
}

}

}

No comments:

Post a Comment