Explain Codes LogoExplain Codes Logo

How to retrieve a file from a server via SFTP?

java
sftp-library
exception-handling
stream-processing
Alex KataevbyAlex Kataev·Feb 20, 2025
TLDR

Retrieve a file via SFTP in Java using JSch:

import com.jcraft.jsch.*; public class SFTPDownload { public static void main(String[] args) { String host = "sftp.example.com"; String user = "username"; String pwd = "password"; String remoteFile = "/remote/file.txt"; String localDir = "/local/dir"; JSch jsch = new JSch(); Session session = jsch.getSession(user, host, 22); session.setConfig("StrictHostKeyChecking", "no"); // He's a free spirit session.setPassword(pwd); session.connect(); // Where the magic Happens ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp"); sftpChannel.connect(); // Keep the good vibes flowing sftpChannel.get(remoteFile, localDir); // grab and bag sftpChannel.disconnect(); // Bye, Felicia! session.disconnect(); // Time to break up } }

Connect to SFTP, configure session to bypass strict host key checking (for testing only), download the file, and then clean up the connections.

SFTP Library Choice

Deciding on an SFTP client library depends on your project's requirements. JSch, Apache Commons VFS, or SSHJ are your likely candidates. The latter offers a more streamlined, modern approach whilst not compromising functionality.

Handling Connection and Authentication

A secure connection is at the heart of any SFTP operation. JSch provides methods to set known hosts and handles both password and key-based authentication. However, remember to verify host keys in a production environment.

Handling Large Files

Working with substantial file sizes? Optimize by using methods that allow stream processing, thereby avoiding exhausting your system resources (and your patience!).

Be Exception-ally Good!

Thorough exception handling is not just practicing good coding etiquette, but also ensures the resilience of your system. Similarly, remember to close your sessions and channels post transfer to avoid resource starvation.

The Other Tools in your Toolbox

Apache Commons VFS and SSHJ are two other libraries that can come handy based on your requirements. Want an abstract representation of your file system? FileSystemManager of the Apache Commons VFS is your friend. Looking for a more modern, intuitive API? Give SSHJ a spin.