Using SFTP with Java

Learn about connecting to an SFTP server and Couchdrop with Java.

How to use SFTP with Java

To use SFTP with Java, you can leverage the JSch library, which provides support for SSH communication in Java. Below is a basic guide on how to use JSch to interact with SFTP servers:

  1. Add JSch Dependency: First, you need to include the JSch library in your Java project. You can do this by adding the dependency to your Maven or Gradle configuration, or by downloading the JAR file and including it in your project manually.

    For Maven, add the following dependency to your pom.xml file:

    <dependency>
        <groupId>com.jcraft</groupId>
        <artifactId>jsch</artifactId>
        <version>0.1.55</version>
    </dependency>
  2. Create SFTP Connection: Below is an example of how to connect to an SFTP server using JSch:

    import com.jcraft.jsch.ChannelSftp;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.Session;
    
    public class SFTPExample {
        public static void main(String[] args) {
            String host = "sftp.example.com";
            String username = "your_username";
            String password = "your_password";
            int port = 22;
    
            try {
                JSch jsch = new JSch();
                Session session = jsch.getSession(username, host, port);
                session.setPassword(password);
                session.setConfig("StrictHostKeyChecking", "no");
                session.connect();
    
                ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
                sftpChannel.connect();
    
                // Now you can perform SFTP operations using sftpChannel
    
                // Close the SFTP channel and session when done
                sftpChannel.disconnect();
                session.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
  3. Perform SFTP Operations: Once you've established an SFTP connection, you can perform various operations such as uploading files, downloading files, listing directory contents, creating directories, etc. Here are a few examples:

    • Upload a file:

      sftpChannel.put("/path/to/local/file.txt", "/path/to/remote/file.txt");
    • Download a file:

      sftpChannel.get("/path/to/remote/file.txt", "/path/to/local/file.txt");
    • List directory contents:

      String files = sftpChannel.ls("/path/to/remote/directory"); 
  4. Close the Connection: After you've finished with the SFTP operations, make sure to close the SFTP channel and the SSH session:

    sftpChannel.disconnect();
    session.disconnect();

By following these steps, you can use Java with JSch to interact with SFTP servers and perform various file operations. Make sure to handle exceptions appropriately when dealing with network connections and file operations.

Last updated