NCiphers SFTP4J offers simple but powerful API that allows us to implement SFTP communication in a Java application. This tutorial will introduce the main functions offered by the SFTP4J library and will demonstrates with short examples how to utilize them.
List of examples in Sftp4J Tutorial
- Class
- Connecting and disconnecting
- Remote path
- Uploading
- Downloading
- File properties: exists, type, size, modification time
- Listing remote folders
- Creating folders
- Deleting files and folders
- Touch file
- Exception handling
Class
The main class of the library is com.nciphers.sftp.Sftp. It has to be instantiated before any SFTP activity.
Connecting and disconnecting
Before we can start any SFTP activity with a remote SFTP host, we must have been granted access credentials upfront. This is usually done by the system administrator of the SFTP server machine.
An SFTP connection is authenticated with either a username and a password, or with a username and an SSH key. In the case with an SSH key, our public key must have been installed on the SFTP server and we have to provide the private SSH key to the SFTP4J library in order to sign the connection request. Below you can see both approaches:
import com.nciphers.sftp.Sftp; // connect with password Sftp sftp = new Sftp(); try { sftp.connect(Settings.host, Settings.username, Settings.password); } finally { sftp.disconnect(); } // connect with SSH private key Sftp sftp = new Sftp(); try { sftp.connect(Settings.host, Settings.user, Settings.keyFileLocation, Settings.keyFilePassword); } finally { sftp.disconnect(); }
Proxy
If your application must tunnel the Internet connection through a proxy server, you can specify the proxy address with:
Sftp sftp = new Sftp(); sft.setProxy("10.0.0.100", 8000); // IP and Port of the proxy server
Remote path
The remote path on the SFTP server starts with a root which is “/” and from there on we can construct folders and sub folders with files, etc. Here are some valid file and folder paths for an SFTP server:
/ /my_remote_folder /my_remote_folder/sub_folder/my_file.dat
The com.nciphers.sftp.Sftp class works internally with a current path, which initially is set to the current account root folder “/”. We can get the current path with
String remotePath = sftp.getCurrentPath();
and set the remote path with:
sftp.setCurrentPath("/my_remote_folder");
Addressing remote files and folders
Remote files and folders can be addressed absolutely (full path relative from the account root folder) like:
/my_remote_folder/sub_folder/my_file.dat
or relatively from the current path ; after invoking sftp.setCurrentPath(“/my_remote_folder”) the below path is the same as the absolute one above
sub_folder/my_file.dat
Uploading data
We can upload a local file or directly write the contents of an InputStream or byte array to a remote file on the SFTP host. Below you can see both examples:
Sftp sftp = new Sftp(); try { sftp.connect(Settings.host, Settings.user, Settings.keyFile, Settings.keyPassword); // upload file sftp.putFile("examples/data/file.txt", "file_on_server.txt"); // upload input stream InputStream data = new ByteArrayInputStream("Hello World".getBytes("UTF-8")); sftp.putFile(data, "file_on_server.txt"); data.close(); } finally { sftp.disconnect(); }
Downloading
When downloading we have similar options like in the upload scenario: download to a local file or to an OutputStream:
Sftp sftp = new Sftp(); try { sftp.connect(Settings.host, Settings.user, Settings.keyFile, Settings.keyPassword); // download to a local file sftp.getFile("file_on_server.txt", "examples/data/file.txt"); // get the contents of a remote file byte[] remoteContents = sftp.getFileBytes("file_on_server.txt"); } finally { sftp.disconnect(); }
File properties
We can observer different properties of a remote file. The example below illustrates some of the possibilities:
Sftp sftp = new Sftp(); try { sftp.connect(Settings.host, Settings.user, Settings.keyFile, Settings.keyPassword); String fileName = "file_on_server.txt"; if (sftp.exists(fileName)) { System.out.println("File size is " + sftp.fileSize(fileName) + " bytes"); System.out.println("Last modified on " + sftp.lastModified(fileName)); if (sftp.isDirectory(fileName)) { System.out.println(fileName + " is directory"); } else if (sftp.isFile(fileName)) { System.out.println(fileName + " is regular file"); } } else { System.out.println(fileName + " does not exist on server"); } } finally { sftp.disconnect(); }
Listing remote folders
We can get the contents of a remote folder with one of the Sftp.list methods. The general list methods returns all items in a remote folder. listFiles and listDirs return only the files or folders respectively:
Sftp sftp = new Sftp(); try { sftp.connect(Settings.host, Settings.user, Settings.keyFile, Settings.keyPassword); SftpItem[] files = sftp.list(); for (int i = 0; i < files.length; i++) { System.out.print(files[i].getName()); System.out.print(" - "); if (files[i].isDirectory()) { System.out.print("<DIR>"); } else if (files[i].isFile()) { System.out.print("FILE"); } else if (files[i].isSymplink()) { System.out.print("LINK"); } System.out.print(" - "); System.out.print(files[i].getModificationTime()); System.out.println(); } } finally { sftp.disconnect(); }
Creating folders
Remote folder can be created with the Sftp.createDir method:
Sftp sftp = new Sftp(); try { sftp.connect(Settings.host, Settings.user, Settings.keyFile, Settings.keyPassword); sftp.createDir("myfolder"); } finally { sftp.disconnect(); }
Deleting files and folders
Files and folders are deleted through the Sftp.deleteFile and Sftp.deleteDir methods:
Sftp sftp = new Sftp(); try { sftp.connect(Settings.host, Settings.user, Settings.keyFile, Settings.keyPassword); sftp.deleteDir("myfolder"); sftp.deleteFile("myfile.txt"); } finally { sftp.disconnect(); }
Touch file
The touch command is used to set the last modification time of a file to a certain Date:
Sftp sftp = new Sftp(); try { sftp.connect(Settings.host, Settings.user, Settings.keyFile, Settings.keyPassword); boolean touched = sftp.touch("file_on_server.txt", new Date()); if (touched) { System.out.println("File file_on_server.txt modification time has been modified"); } else { System.out.println("Problem occured setting file modification time - check file exists, read-only, etc."); } } finally { sftp.disconnect(); }
Exception handling
The SFTP4J library offers custom exception types derived from java.io.IOException and located in the com.nciphers.exceptions package. The main exception type that can be expected from SFTP related activity is com.nciphers.exceptions.SftpException and in your application exception handling block you may first check for it :
Sftp sftp = new Sftp(); try { sftp.connect(Settings.host, Settings.user, Settings.keyFile, Settings.keyPassword); sftp.... } catch (SftpException) { System.out.println("SFTP exception: " + e.getMessage()); }
When connecting two additional exception can be handled:
WrongKeyPasswordException – if connecting with SSH private key and the key password is incorrect.
AuthenticationException – if the provided key, username or password is not accepted by the server
Summary
This chapter is was a short introduction to the SFTP methods offered in com.nciphers.sftp.Sftp class
List of methods
Name | Description |
---|---|
Sftp.connect | establishes connection with remote SFTP host |
Sftp.disconnect | disconnects from remote SFTP host |
Sftp.putFile | uploads file |
Sftp.upload | uploads file |
Sftp.getFile | downloads file |
Sftp.download | downloads file |
Sftp.list | lists remote items |
Sftp.listFiles | lists remote files |
Sftp.listDirs | lists remote folders |
Sftp.createdDir | creates remote directory |
Sftp.deleteDir | deletes remote directory |
Sftp.deleteFile | deletes file |
Sftp.touch | sets remote file last modification time |
Sftp.fileSize | returns file in bytes |
Sftp.lastModified | returns file last modification time |
Sftp.exists | checks does a remote item exist |
Sftp.isDirectory | checks is a remote item a directory |
Sftp.isFile | checks is a remote item a file |
Sftp.setProxy | sets proxy host for the connection |
Sftp.getCurrentPath | current path on the server |
Sftp.setCurrentPath | sets current path on the server |