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
  • 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.

  • Sam De

    does com.kodehelp.sftp need a license?

    • http://kodehelp.com/ Deekay

      @Sam – You don’t require any license to use the code which is given in this article.

  • Kushal

    I am getting No such file exception

  • Kushal

    Getting below error

    2: No such file

    at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2630)

    at com.jcraft.jsch.ChannelSftp._realpath(ChannelSftp.java:2161)

    at com.jcraft.jsch.ChannelSftp.cd(ChannelSftp.java:315)

    at com.kodehelp.sftp.SFTPinJava.main(SFTPinJava.java:53)

    • http://kodehelp.com/ Deekay

      @Kushal – Please make sure you have given correct path for the file which you are trying to upload. Check the below statement in you code File f = new File(FILETOTRANSFER);

      • bkm

        Hi Deekay, I have used the below statement to move my file to remote

        String FILETOTRANSFER = “/temp”; // this is the path where i need to push the file from local(C:/Data/sonar/bnyprojects_metrics_new4.csv).

        But i am getting the below exception

        2: No such file
        at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2846)
        at com.jcraft.jsch.ChannelSftp._realpath(ChannelSftp.java:2340)
        at com.jcraft.jsch.ChannelSftp.cd(ChannelSftp.java:342)
        at com.bnymellon.sonar.Integrator.SFTPinJava.main(SFTPinJava.java:53)

        Could you please help on this:

        Code Below. Please correct if anything here

        public static void main(String[] args) {
        String SFTPHOST = “hostname”;
        int SFTPPORT = 22;
        String SFTPUSER = “user”;
        String SFTPPASS = “password”;
        String SFTPWORKINGDIR = “C:/Data/sonar/bnyprojects_metrics_new4.csv”;
        String FILETOTRANSFER = “/temp”;
        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);
        // File inputFile = new File(FILETOTRANSFER);

        channelSftp.put(new FileInputStream(f), f.getName());
        }catch(Exception ex){
        ex.printStackTrace();
        }

        }

        }

      • bkm

        Hi Deekay, I have used the below statement to move my file to remote

        String
        FILETOTRANSFER = “/temp”; // this is the path where i need to push the
        file from local(C:/Data/filename.csv).

        But i am getting the below exception

        2: No such file
        at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2846)
        at com.jcraft.jsch.ChannelSftp._realpath(ChannelSftp.java:2340)
        at com.jcraft.jsch.ChannelSftp.cd(ChannelSftp.java:342)
        at com.bnymellon.sonar.Integrator.SFTPinJava.main(SFTPinJava.java:53)

        Could you please help on this:

        Code Below. Please correct if anything here

        public static void main(String[] args) {
        String SFTPHOST = “hostname”;
        int SFTPPORT = 22;
        String SFTPUSER = “user”;
        String SFTPPASS = “password”;
        String SFTPWORKINGDIR = “C:/Data/myfile.csv”;
        String FILETOTRANSFER = “/temp”;
        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);
        // File inputFile = new File(FILETOTRANSFER);

        channelSftp.put(new FileInputStream(f), f.getName());
        }catch(Exception ex){
        ex.printStackTrace();
        }

        }

        }

        • http://kodehelp.com/ Deekay

          @bkm- you need to correct SFTPWORKINGDIR and FILETOTRANFER values. Please see below corrected values –
          String SFTPWORKINGDIR = “/temp”;
          String FILETOTRANSFER = “C:/Data/myfile.csv”;

  • Varun Krishna

    When I run this code I am getting the following error

    4: The requested operation failed.

    at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2833)
    at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:2185)
    at com.jcraft.jsch.ChannelSftp.cd(ChannelSftp.java:343)
    at SFTPinJava.main(SFTPinJava.java:56)
    How do I fix this guys? What am I missing?

    Thanks,
    Varun Krishna. P

    • http://kodehelp.com/ Deekay

      @varun_krishna:disqus – Please make sure you have correct path in channelSftp.cd(SFTPWORKINGDIR);

      • Varun Krishna

        @Deekay Yeah, initially I had pointed to the wrong directory in the line 38. then did some change to it and it worked fine. Since I am using windows, it supports something like this “folder_name/” and it doesn’t support “/folder_name/”. Thanks. Deekay at com.jcraft.jsch.ChannelSftp.cd(ChannelSftp.java:343) this is the clue right?

        • http://kodehelp.com/ Deekay

          @varun_krishna:disqus – That the clue. you are right :) Glad to hear that your issue is fixed.

          • Guest

            Deekay I have one more question/doubt about the error message at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2833)
            at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:2185)

            Why am I getting these two lines in my error message, when the problem is with the path mentioned in String SFTPWORKINGDIR? Could you please explain it to me?
            I would say that your tutorial is awesome :)
            Thanks,
            Varun Krishna. P

  • karthik

    I am able to copy the file content to the server with limitation as below
    1st line on the remote file as
    xyz.abc.com ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAp8wCyUgYWpmMEau1s/G2yy8Pow8nIoB1JuG8yrlLeAUtGeMq3rODDHyyxzMhExyC7kHeTiCCal31WSF62OkZo8N/gc8Uu3p+jkpdi48M7IiXwD2NrbAQKYeQmiSSP7T1VFxMH5oxGcYzRVV6CEGTFDTrkyFXwg0fekcLrjmHN5lovTH9ptlUjks7zGFJFNMDB6r7LpUbYjx6zpbhs+/nOEn4hdlCotWjbfIM+uqRVvdfz4eGISgdmPyYYQSlwJ8W58eaAfTbEyluN3e2JNoaJ9LxC391Q/o0EA4Yx3pycsFeRIRjmJyoYOFfACRzw/zS/Bv/79ZlcRA/9tIdyl05vQ==

    Can any one help me, How to avoid this?

    Thanks in advance

  • ajay

    How to find my sftp working directory. I am using ubuntu.

  • Guest

    channelSftp.put(new
    FileInputStream(f), f.getName()); – See more at:
    http://kodehelp.com/java-program-for-uploading-file-to-sftp-server/#sthash.4bvDMft1.dpuf

  • Nitesh Komalwar

    line no 58:
    channelSftp.put(new FileInputStream(f), f.getName());

    this will result in creating new file input stream, and will keep the file in use until the program is not terminated.
    instead you must use

    FileInputStream fis = new FileInputStream(f);
    channelSftp.put(fis, f.getName());
    fis.close();

    so that the file input stream is properly closed.

    • http://kodehelp.com/ Deekay

      @niteshkomalwar:disqus – Thanks for pointing this out. I have corrected the code.

  • arpit

    How to automated sftp file transfer,