How to Retrieve a File from a Server Using SFTP in Java
When attempting to retrieve a file from a remote server using SFTP, an esteemed option is the JSch library. It's a coveted choice for projects like Eclipse, Ant, and Apache Commons HttpClient, offering robust features including both user/pass and certificate-based logins.
To demonstrate SFTP retrieval using JSch, we present a simplified example:
import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; public class SftpFileRetrieval { public static void main(String[] args) throws Exception { // Establish a JSch session JSch jsch = new JSch(); Session session = jsch.getSession("remote-username", "remote-host"); session.setPassword("remote-password"); session.connect(); // Open an SFTP channel Channel channel = session.openChannel("sftp"); channel.connect(); // Get the SFTP channel ChannelSftp sftpChannel = (ChannelSftp) channel; // Retrieve the file sftpChannel.get("remote-file", "local-file"); // Close the channel and session sftpChannel.exit(); session.disconnect(); } }
Remember to customize the parameters according to your specific server settings. With this code, you can effortlessly retrieve files from remote servers using SFTP in your Java applications.
The above is the detailed content of How to Retrieve Files from an SFTP Server Using Java?. For more information, please follow other related articles on the PHP Chinese website!