Java Program For Uploading File To SFTP Server

By July 1, 2010 at 1:36 am · Java/J2EE, Open Source

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

}

}
email

DeeKay has been working in Java, JEE and opensource technology since 7 years and has same years of experience in software development. His area of interest is TDD, Scala langauge, Java, JEE techologies.

This author has published 208 articles so far.

Related Posts

Popular Posts

  • Andy

    Hi,

    I get following error.

    com.jcraft.jsch.JSchException: Auth cancel
    at com.jcraft.jsch.Session.connect(Session.java:451)
    at com.jcraft.jsch.Session.connect(Session.java:150)

    Please help.

    Thanks,
    Andy

    • http://www.vigilance.co.in admin

      @Andy – Did you added values for below configurations :

      String SFTPHOST = “10.20.30.40″;
      int SFTPPORT = 22;
      String SFTPUSER = “username”;
      String SFTPPASS = “password”;

      Ans also make sure that you have added “NO” at below statement -
      config.put(“StrictHostKeyChecking”, “no”);

    • http://kodehelp.com/ Deekay

      This might be failing because your private key was failing authentication; please make sure your are passing the password correctly.