Simple SFTP example in Java with Jsch

I use Jsch lib to connect in ssh to a remote sftp server.

The program connects to the server, and then count the number of files in the directory and then displays their contents.

import java.util.Vector;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class DemoSftp {

    public static void main(String[] args) throws JSchException, SftpException {

        String hostname = "hostname";
        String login = "login";
        String password = "password";
        String directory = "the directory";

        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");

        JSch ssh = new JSch();
        Session session = ssh.getSession(login, hostname, 22);
        session.setConfig(config);
        session.setPassword(password);
        session.connect();
        Channel channel = session.openChannel("sftp");
        channel.connect();

        ChannelSftp sftp = (ChannelSftp) channel;
        sftp.cd(directory);
        Vector files = sftp.ls("*");
        System.out.printf("Found %d files in dir %s%n", files.size(), directory);

        for (ChannelSftp.LsEntry file : files) {
            if (file.getAttrs().isDir()) {
                continue;
            }
            System.out.printf("Reading file : %s%n", file.getFilename());
            BufferedReader bis = new BufferedReader(new InputStreamReader(sftp.get(file.getFilename())));
            String line = null;
            while ((line = bis.readLine()) != null) {
                System.out.println(line);
            }
            bis.close();
        }

        channel.disconnect();
        session.disconnect();

    }

}
This entry was posted in java programming, library and tagged , , , . Bookmark the permalink.

7 Responses to Simple SFTP example in Java with Jsch

  1. Gurpreet says:

    Thanks !
    This one made my day.
    Keep up the good work…

  2. Anonymous says:

    It’s very good one and help me so much but the problem is that when I use cd(dir), it doesn’t work.

  3. Anonymous says:

    its a very good one

  4. Anonymous says:

    nice simple and to the point example.

  5. Anonymous says:

    nice

  6. Anonymous says:

    very much clear and crisp code

  7. Anonymous says:

    Thank you for providing the below code , this was very clear for understanding.

Leave a comment