Home > Java > javaTutorial > How Can I Retrieve Files via SFTP in Java Using JSch?

How Can I Retrieve Files via SFTP in Java Using JSch?

Patricia Arquette
Release: 2024-12-14 12:31:10
Original
365 people have browsed it

How Can I Retrieve Files via SFTP in Java Using JSch?

Retrieving Files via SFTP in Java

When utilizing SFTP rather than FTPS to retrieve files from a remote server, Java developers face a unique challenge. One approach is to explore the JSch library, a widely adopted choice for reputable open-source projects like Eclipse, Ant, and Apache Commons HttpClient.

JSch seamlessly accommodates both username/password and certificate-based logins, offering a comprehensive range of SSH2 capabilities. Below, we present a rudimentary example of retrieving a file over SFTP using JSch:

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/Sftp.java in the JSch dist
  UserInfo ui = new MyUserInfo();
  session.setUserInfo(ui);

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

session.connect();

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

ChannelSftp sftpChannel = (ChannelSftp) channel;

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

sftpChannel.exit();
session.disconnect();
Copy after login

The above is the detailed content of How Can I Retrieve Files via SFTP in Java Using JSch?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template