In Creating an SSH Client we demonstrated how to connect to an SSH server and authenticate the user. SFTP is a file transfer protocol that runs over the SSH connection and is now one of the most widely used secure file transfer mechanism.
The SshClient provides a high-level API to perform basic file transfers. If you have a more complex requirement, want to manage file permissions or perform more advanced operations you should take a look at our SftpClientTask which is documented in Implementing an SFTP Client.
Uploading Files
In its simplest form, we can just pass a File object to the putFile method to transfer this to the remote server.
In the example below, a file called maverick.zip will be placed in the users' default directory, which is typically their home directory.
try(SshClient ssh = new SshClient("localhost", 22, "lee", "xxxxxxxx".toCharArray())) {
ssh.putFile(new File("/Users/lee/Downloads/maverick.zip"));
}
If we want to control where the file is placed on the server we can pass the remote path. For example, this places the file in the tmp folder:
ssh.putFile(new File("/Users/lee/Downloads/maverick.zip"). "/tmp");
We can also optionally set a timeout limit. Note, that this is not a socket timeout, this is a time limit on the operation. If the operation fails to complete within the time limit provided an exception will be raised.
ssh.putFile(new File("/Users/lee/Downloads/maverick.zip"). "/tmp", 60000L);
Downloading Files
Similarly, we can download files with getFile methods. Passing the path of the file on the remote server, the file will be downloaded to the same name in the users home directory.
File dest = ssh.getFile("maverick.zip");
We can control where the file is placed by passing our own file instance.
File dest = new File("/tmp");
ssh.getFile("maverick.zip", dest);
And as with all high-level operations, we can provide a timeout value.
ssh.getFile("maverick.zip", dest, 60000L);