
- Image via Wikipedia
Uploading the file to SFTP server is not easy using Java.net API or Apache‘s Commons.net API. Many of you have faced lots of problems using these API. To upload the file SFTP server you have use the JSCH API, you can download the API fromhere. In my previous post i have shown how to download the file from SFTP server. You can read this post here.
Below is the java program for the uploading the file from SFTP server -
/**
*
*/
package com.kodehelp.sftp;
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() {
// TODO Auto-generated constructor stub
}
/**
* @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);
File f = new File(FILETOTRANSFER);
channelSftp.put(new FileInputStream(f), f.getName());
}catch(Exception ex){
ex.printStackTrace();
}
}
}
