Java – How to retrieve a file from a server via SFTP


I'm trying to retrieve a file from a server using SFTP (as opposed to FTPS) using Java. How can I do this?

Best Solution

Another option is to consider looking at the JSch library. JSch seems to be the preferred library for a few large open source projects, including Eclipse, Ant and Apache Commons HttpClient, amongst others.

It supports both user/pass and certificate-based logins nicely, as well as all a whole host of other yummy SSH2 features.

Here's a simple remote file retrieve over SFTP. Error handling is left as an exercise for the reader :-)

JSch jsch = new JSch();

String knownHostsFilename = "/home/username/.ssh/known_hosts";
jsch.setKnownHosts( knownHostsFilename );

Session session = jsch.getSession( "remote-username", "remote-host" );    
  // "interactive" version
  // can selectively update specified known_hosts file 
  // need to implement UserInfo interface
  // MyUserInfo is a swing implementation provided in 
  //  examples/ in the JSch dist
  UserInfo ui = new MyUserInfo();

  // OR non-interactive version. Relies in host key being in known-hosts file
  session.setPassword( "remote-password" );


Channel channel = session.openChannel( "sftp" );

ChannelSftp sftpChannel = (ChannelSftp) channel;

sftpChannel.get("remote-file", "local-file" );
// OR
InputStream in = sftpChannel.get( "remote-file" );
  // process inputstream as needed