- Transferring a File Through SFTP in Java
- Transferring a File Through SFTP in Java
- Use the JSch library
- Configuring JSch
- File Transfer Examples
- Two Complete JSch Examples
- Upload a file
- Download a file.
- Integrate third-party file transferring to your Java application.
- Relevant Features:
- Final Words
- Transferring a File Through SFTP in Java FAQs
- How do I transfer a file through SFTP in Java?
- How do I authenticate with the SFTP server in Java?
- How do I handle errors and exceptions when transferring a file through SFTP in Java?
- Can I transfer multiple files through SFTP in Java at the same time?
- Java — Connecting to SFTP, Uploading & Downloading Files
- Dependencies
- Connecting to SFTP Server
- Uploading File
- Downloading File
- Disconnecting from server
- Full Code
- Ivan Andrianto
Transferring a File Through SFTP in Java
In this post, we’ll go through a few examples of transferring files through SFTP in Java. To accomplish this, we’ll use the JSch library to implement SSH on Java SFTP. Then, we’ll go through setting up JSch, uploading and downloading using JSch put and get, and two complete examples of Java code.
Transferring a File Through SFTP in Java
Before we proceed into Java, let’s quickly define the differences between the popular transferring mechanisms. Transferring a file with File Transfer Protocol (FTP) or FTPS (FTP over SSL) is not the same as doing it with SFTP (Secure FTP or FTP over SSH).
While FTP and FTPS use the same FTP foundation with slight differences, SFTP is an entirely different protocol. SFTP uses the secure shell protocol (SSH) to establish a channel and then transmit data. To authenticate users, SFTP can use a password or public-key authentication, plus it can also encrypt data communications between client and server.
You can use SFTP to connect via SSH to your Java application and then transfer files. With SFTP, you connect using SSH and then transfer files with SFTP. To do this, you can use the JSch (Java secure channel) library.
Use the JSch library
JSch is a Java implementation for the SSH2 protocol. It allows you to connect to an OpenSSH server through the sshd process and use secure file transferring. In addition, it also allows you to use port forwarding and X11 forwarding. JSch supports SSH File Transfer Protocol(version 0, 1, 2, 3).
In addition, to use the package, you can add the following JSch dependencies on your POM.xml file.
You can also find the latest JSch in Maven’s central repository.
Configuring JSch
As mentioned earlier, you can use Password or Public key authentication for remote server access with JSch. For example, if you want to set up password authentication:
private ChannelSftp setupJsch() throws JSchException
Session jschSession = jsch.getSession(username, remote_host, remote_port);
return (ChannelSftp) jschSession.openChannel(“sftp”);
Where the variables “remote_host” represent the IP of the SFTP server and “remote_port” the port to be used (22, for example).
File Transfer Examples
With JSch, you can use the “put” and “get” for your file transfers between the SFTP client and server. For example, you can use “put” to upload a file from a local SFTP client to a remote SFTP server.
Use com.jcraft.jsch.ChannelSftp.put:
channelSftp.put(localFile, remoteFile); |
And, you can use “get” to download or transfer a file from a remote SFTP server to the local SFTP client. Use com.jcraft.jsch.ChannelSftp.get
channelSftp.get(remoteFile, localFile); |
Two Complete JSch Examples
Below are two complete working examples of Java code using JSch to transfer files between two SFTP endpoints. The code checks the credentials (not key), connects to the server, and opens an SFTP channel.
Upload a file
The below example uploads a file from the SFTP server using JSch SFTP put.
public void send (String fileName)
String SFTPUSER = “username”;
String SFTPPASS = “password”;
String SFTPWORKINGDIR = “file/to/transfer”;
ChannelSftp channelSftp = null;
System.out.println(“preparing the host information for sftp.”);
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
java.util.Properties config = new java.util.Properties();
System.out.println(“sftp channel opened and connected.”);
channelSftp = (ChannelSftp) channel;
channelSftp.put(new FileInputStream(f), f.getName());
log.info(“File transfered successfully to host.”);
System.out.println(“Exception found while tranfer the response.”);
System.out.println(“sftp Channel exited.”);
System.out.println(“Host Session disconnected.”);
Download a file.
A similar example of Java code also uses the JSch API to download a file from the SFTP server using “get.”
public static void main(String[] args)
String SFTPUSER = “username”;
String SFTPPASS = “password”;
String SFTPWORKINGDIR = “/file/to/get”;
ChannelSftp channelSftp = null;
System.out.println(“preparing the host information for sftp.”);
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
java.util.Properties config = new java.util.Properties();
System.out.println(“sftp channel opened and connected.”);
channelSftp = (ChannelSftp) channel;
byte[] buffer = new byte[1024];
BufferedInputStream bis = new
File newFile = new File(“C:/Test.txt”);
OutputStream os = new FileOutputStream(newFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
while ((readCount = bis.read(buffer)) > 0)
bos.write(buffer, 0, readCount);
The idea is to break up the actions into separate blocked statements (try <> and catch <>). This approach will ultimately help with better granular error reporting and include informational outputs that would inform the status of the action to the end-user.
Integrate third-party file transferring to your Java application.
Files.com is a cloud-based file transferring service that supports standard mechanisms, including SFTP and many more. In addition, Files.com allows you to integrate with Java via their SDK or into your Java app via their REST API.
Relevant Features:
- Files.com’ REST API: Provides the functionality of the Files.com platform to allow your Java application to integrate seamlessly to Files.com. With this REST API, you could, for example, transfer files via SFTP via a custom application or web portal, provide reporting and analytics, and more.
- Files.com’s Java SDK: The Files.com Java client library provides easy access to Files.com’s API from your Java applications. Files.com’s Java SDK can be installed via GitHub.
- Support for many SFTP libraries. Files.com also supports the JSch library.
ExaVault.com is another file storage system that offers SFTP server functions that can be accessed through an API. This tool also offers an FTPS option. The ExaVault system can be integrated into a JavaScript program in two ways:
- ExaVault API: This function can be called from any program. You just need to set up the call with the right variables in order to send a file through your automated system through ExaVault’s SFTP server.
- ExaVault libraries: ExaVault has libraries of functions available in its GitHub account that allow direct access to the platform’s functions. These code libraries are available in JavaScript, Java, PHP, and Python.
Final Words
In this post, we learned the brief differences between SFTP and the other popular transferring mechanisms. We learned how to upload and download from (and to) the SFTP server using Java. We used the JSch library and provided examples with the put and get.
Transferring a File Through SFTP in Java FAQs
How do I transfer a file through SFTP in Java?
To transfer a file through SFTP in Java, you need to use a library or API that provides SFTP functionality. Some popular options include JSch, Apache MINA SSHD, and Spring Integration SFTP. These libraries provide methods for connecting to an SFTP server, authenticating, and transferring files. You will need to write code using the methods provided by these libraries to connect to the SFTP server, authenticate, and transfer the file.
How do I authenticate with the SFTP server in Java?
The process of authenticating with the SFTP server in Java will depend on the library or API you are using. However, in general, you will need to provide the SFTP server’s hostname, username, and password. Some libraries may also support other forms of authentication, such as private key authentication.
How do I handle errors and exceptions when transferring a file through SFTP in Java?
When transferring a file through SFTP in Java, it’s important to handle errors and exceptions that may occur during the transfer process. You can use try-catch blocks to catch exceptions and handle them appropriately. Additionally, you should check the return values of the SFTP methods you use to ensure that the file transfer was successful.
Can I transfer multiple files through SFTP in Java at the same time?
Yes, it’s possible to transfer multiple files through SFTP in Java simultaneously. You can use a loop and call the SFTP file transfer method for each file you want to transfer. Or use a library like Apache Commons VFS that can handle multiple file transfers at the same time.
Java — Connecting to SFTP, Uploading & Downloading Files
SFTP (SSH File Transfer Protocol; also known as Secure File Transfer Protocol) is a protocol packaged with SSH for transferring files between computers. Because of its security, SFTP is often preferable to FTP, and therefore many systems have been migrating from FTP to SFTP. Sometimes the process of uploading or downloading files needs to be handled by the back end of an application. In this tutorial, I’m going to show you how to connect to an SFTP server with Java, including how to get authenticated as well as how to upload and download a file.
Dependencies
We’re going to use com.jcraft.jsch as the library for connecting to SFTP server. Add it to the dependencies of your project. Below are the example if you use maven and gradle. Just adjust it yourself if you’re using other dependency manager.
build.gradle
compile 'com.jcraft:jsch:0.1.55'
Connecting to SFTP Server
To make to code reusable and more readable, it’s better to create a helper class which includes the methods for connecting to SFTP server as well as uploading and downloading files.
For connecting to an SFTP server, first create an instance of JSch . If you need to provide certificate for authentication, you can use addIdentity . Then create a session of the JSch sesion using jsch.getSession . If the server requires password, we can use setPassword and modify the way we use jsch.getSession , as exemplified below.
package com.woolha.example.helpers; public class SFTPClient < private String host = "ftp.example.com" private int port = 22; private Session session = null; public SFTPClient() < >public void connect() throws JSchException < JSch jsch = new JSch(); // Uncomment the line below if the FTP server requires certificate // jsch.addIdentity("private-key-path); session = jsch.getSession(server); // Comment the line above and uncomment the two lines below if the FTP server requires password // session = jsch.getSession("username", host, port); // session.setPassword("the-password"); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); >>
Uploading File
Having connected and authenticated to the SFTP server, we can upload a file by creating a new ChannelSftp and use its put method. The first argument is the path of the local file, while the second argument is the destination path in the SFTP server.
public void upload(String source, String destination) throws JSchException, SftpException
Downloading File
To download a file, we also need to create a new ChannelSftp . Then, use get method with the first argument is the path of the file in SFTP server and the second argument is the local path where the file be downloaded.
public void download(String source, String destination) throws JSchException, SftpException
Disconnecting from server
After we have done the operations, we need to cut the connection to the server.
Full Code
Below is the full code of the helper.
package com.woolha.example.helper; import com.jcraft.jsch.*; public class SFTPClient < private Session session = null; @Value("$") private String privateKeyPath; public void connect() throws JSchException < JSch jsch = new JSch(); // Uncomment the line below if the FTP server requires certificate jsch.addIdentity("private-key-path); session = jsch.getSession(server); // Uncomment the two lines below if the FTP server requires password session = jsch.getSession("username", host, port); session.setPassword("the-password"); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); >public void upload(String source, String destination) throws JSchException, SftpException < Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; sftpChannel.put(source, destination); sftpChannel.exit(); >public void download(String source, String destination) throws JSchException, SftpException < Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; sftpChannel.get(source, destination); sftpChannel.exit(); >public void disconnect() < if (session != null) < session.disconnect(); >> >
Upload Example
SFTPClient sftpClient = new SFTPClient(); sftpClient.connect(); sftpClient.upload("images/img1.png", "images/img1_server.png"); sftpClient.disconnect();
Download Example
SFTPClient sftpClient = new SFTPClient(); sftpClient.connect(); sftpClient.download("images/img1_server.png", "images/img1_downloaded.png", ); sftpClient.disconnect();
Ivan Andrianto
Ivan Andrianto is a software engineer and the founder of woolha.com. I create high-quality programming tutorials for free.
Maintaining this site requires a lot of effort and server cost. If you find my tutorials helpful, please donate me by buying me a coffee.