Radhakrishna Gorenta Radhakrishna Gorenta - 1 year ago 103
Java Question

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.

Answer Source

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());
            log.info("File transfered successfully to host.");
        } catch (Exception ex) {
             System.out.println("Exception found while tranfer the response.");

            System.out.println("sftp Channel exited.");
            System.out.println("Channel disconnected.");
            System.out.println("Host Session disconnected.");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download