Overview
This article will demonstrate how to securely transfer files using the SFTP (FTP over SSH) protocol and the components provided in Secure FTP Factory or Secure iNet Factor. To see what else these components have to offer please download a FREE 30 day evaluation here, Secure FTP Factory Evaluation and Secure iNet Factory Evaluation.
Note: This example demonstrates transferring files using SFTP (FTP over SSH). If you want to learn how to use FTPS (FTP over SSL) protocol to transfer files then please see the article Secure FTP using Java and FTPS (FTP over SSL)
Prerequisites
- An SSH server with SFTP subsystem enabled
- JDK 1.4 or above
- Secure FTP Factory or Secure iNet Factory
Downloading Files From an SFTP Server using the Sftp Class
The Sftp class provides an easy to use client application programming interface for transferring files between a client and an SFTP subsystem within an SSH (Secure SHell) server.
Please note that the Sftp class is included in both Secure FTP Factory and Secure iNet Factory.
There are two ways to define a class that use Sftp class. If you want to listen to events fired by the Sftp instance you could have your class implement the SftpListener interface or extend the SftpAdapater class, which already implements SftpListener and provides a default implementation.
//import the necessary interface/class
import com.jscape.inet.sftp.events.SftpAdapter;
public class SFtpMdownloadTutorial extends SftpAdapter {
…
}
Or if not interested on listening to SFTP events then a plain Java class will do.
public class SFtpMdownloadTutorial {
…
}
The following code snippet uses the Sftp class to connect to an SFTP subsystem within an SSH server and download files matching a given regex filter.
//import the necessary classes
import com.jscape.inet.sftp.Sftp;
import com.jscape.inet.sftp.SftpException;
import com.jscape.inet.ssh.util.SshParameters;
…
// perform multiple file download
public void doDownload(String sftpHostname, String sftpUsername, String sftpPassword, String filter)
throws SftpException
{
// create/initialize an Sftp instance
SshParameters params = new SshParameters(sftpHostname, sftpUsername, sftpPassword);
Sftp ftp = new Sftp(params);
//capture FTP related events when applicable (if your class extends SftpAdapter or implements FtpListener)
ftp.addSftpListener(this);
// establish connection
ftp.connect();
// download files matching regex filter
ftp.mdownload(filter);
// disconnect
ftp.disconnect();
}
…
Download the complete Java code for this tutorial here: SFtpMdownloadTutorial.java
Summary
Being able to transfer files securely is sometimes a critical requirement to some applications. Using Secure FTP Factory or Secure iNet Factor you can quickly and easily enable such functionality within your applications.
References
Comments