SFTP in Java

Introduction

This demonstrates how Java clients can connect to SFTP servers to transfer files, using edtFTPj/PRO.

Detail

SFTP is a protocol for transferring files securely via the SSH protocol. File transfer commands are implemented on top of SSH. For Java clients to communicate to SFTP servers, the client side of the SFTP protocol and SSH must be implemented in Java.

It is not realistic for most applications to directly implement the SFTP protocol. Instead, it is best to acquire an implementation that is well tested and feature rich - for example, edtFTPj/PRO. The following example demonstrates how a client using edtFTPj/PRO can connect to an SFTP server and list the current directory on the server. It downloads every file in the directory:

import com.enterprisedt.net.ftp.*;

SecureFileTransferClient client = new SecureFileTransferClient();

// set params
client.setRemoteHost(host);
client.setUserName(username);
client.setPassword(password);
client.setProtocol(Protocol.SFTP);

client.connect();

// get a directory listing
FTPFile[] files = client.directoryList();
for (int i = 0; i < files.length; i++) {
 System.out.println(files[i].toString());
 client.downloadFile(files[i].getName(), files[i].getName());
}

client.disconnect();