how to transfer a file through SFTP in java?


How to transfer a file through SFTP in java? I want sample code for SFTP client. I want to embed the SFTP server in my application and the client should able to send a file to my application.

PS: This was asked for SFTP client. And This question is not a duplicate of other two questions.

Find the below link to implement SFTP.

This question is tagged with java file sftp edi b2b

~ Asked on 2013-02-12 10:17:07

The Best Answer is


Try this code.

public void send (String fileName) {
    String SFTPHOST = "host:IP";
    int SFTPPORT = 22;
    String SFTPUSER = "username";
    String SFTPPASS = "password";
    String SFTPWORKINGDIR = "file/to/transfer";

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    System.out.println("preparing the host information for sftp.");

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        System.out.println("Host connected.");
        channel = session.openChannel("sftp");
        System.out.println("sftp channel opened and connected.");
        channelSftp = (ChannelSftp) channel;;
        File f = new File(fileName);
        channelSftp.put(new FileInputStream(f), f.getName());"File transfered successfully to host.");
    } catch (Exception ex) {
        System.out.println("Exception found while tranfer the response.");
    } finally {
        System.out.println("sftp Channel exited.");
        System.out.println("Channel disconnected.");
        System.out.println("Host Session disconnected.");

~ Answered on 2013-02-12 10:46:58

Most Viewed Questions: