Home > Java > javaTutorial > How to Retrieve Files from an SFTP Server Using Java?

How to Retrieve Files from an SFTP Server Using Java?

Linda Hamilton
Release: 2024-12-03 09:09:10
Original
752 people have browsed it

How to Retrieve Files from an SFTP Server Using Java?

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();
    }
}
Copy after login

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!

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