SCP a file in Java using JSch

A simple example of how to use JSch to copy a file using SFTP, from a system that uses passwords, rather than public keys.

private static void sftpFile(File localFile, String username, String password, String hostname, String remoteDirectory)
            throws JSchException, SftpException, FileNotFoundException {
        JSch jsch = new JSch();
        String filename = localFile.getName();
        Session session = jsch.getSession(username, hostname, 22);
        session.setUserInfo(new HardcodedUserInfo(password));
        Properties config = new Properties();
        config.setProperty("StrictHostKeyChecking", "no");
        ChannelSftp channel = (ChannelSftp)session.openChannel("sftp");
        channel.put(new FileInputStream(localFile), filename);
    private static class HardcodedUserInfo implements UserInfo {
        private final String password;
        private HardcodedUserInfo(String password) {
            this.password = password;
        public String getPassphrase() {
            return null;
        public String getPassword() {
            return password;
        public boolean promptPassword(String s) {
            return true;
        public boolean promptPassphrase(String s) {
            return true;
        public boolean promptYesNo(String s) {
            return true;
        public void showMessage(String s) {
            System.out.println("message = " + s);
comments powered by Disqus