Thursday, March 29, 2018

Cool Java client library for secure FTP

My team was looking for a library to PUT and GET files from a sftp server. We used the cool Java library called jSch (www.jcraft.com/jsch/).

Sample code to download and upload files to the SFTP server is given below..

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class SFTPTest{
static String username = "username";
static String host ="ftp.ftpserver.com";
static int port = 22;
static String password = "myPwd";
static String sourceFile = "MySourceFile.csv";
static String targetFile = "MyTargetFile.csv";
public static void main(String[] arg) {
upload();
}
public static void upload() {
try {
//Set the properties and connect to the SFTP server
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
//Open the chnnel and PUT the file to the target folder
Channel channel = session.openChannel("sftp");
channel.connect();
System.out.println("Connected to FTP");
ChannelSftp channelSftp = (ChannelSftp) channel;
channelSftp.put(sourceFile, targetFile, ChannelSftp.OVERWRITE);
//GET THE FILE FROM THE SERVER
channelSftp.get("FromServer.txt", "ToLocal.txt", ChannelSftp.OVERWRITE);
channelSftp.exit();
session.disconnect();
System.out.println("File uploaded successfully!");
} catch (Exception ex) {
System.out.println("File uploaded failed!");
ex.printStackTrace();
}
}
}
view raw SFTP.java hosted with ❤ by GitHub

No comments:

Post a Comment