We may earn a commission if you make a purchase through the links on our website.

Transferring a File Through SFTP in Java

Transferring a file through SFTP using Java

Diego Asturias UPDATED: February 6, 2023

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).

Download JSCH's API from SourceForge.net.

In addition, to use the package, you can add the following JSch dependencies on your POM.xml file.

<dependency>

<groupId>com.jcraft</groupId>

<artifactId>jsch</artifactId>

<version>0.1.55</version>

</dependency>

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 {

JSch jsch = new JSch();

jsch.setKnownHosts(“/home/Users/diego/.ssh/known_hosts”);

Session jschSession = jsch.getSession(username, remote_host, remote_port);

jschSession.setPassword(password);

jschSession.connect();

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.

 

import com.jcraft.jsch.Channel;

import com.jcraft.jsch.ChannelSftp;

import com.jcraft.jsch.JSch;

import com.jcraft.jsch.Session;

public void send (String fileName) {

String SFTPHOST = “host:IP”;

int SFTPPORT = 22;

String SFTPUSER = “username”;

String SFTPPASS = “password”;

String SFTPWORKINGDIR = “file/to/transfer”;

Session session = null;

Channel channel = null;

ChannelSftp channelSftp = null;

System.out.println(“preparing the host information for sftp.”);

try {

JSch jsch = new JSch();

session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);

session.setPassword(SFTPPASS);

java.util.Properties config = new java.util.Properties();

config.put(“StrictHostKeyChecking”, “no”);

session.setConfig(config);

session.connect();

System.out.println(“Host connected.”);

channel = session.openChannel(“sftp”);

channel.connect();

System.out.println(“sftp channel opened and connected.”);

channelSftp = (ChannelSftp) channel;

channelSftp.cd(SFTPWORKINGDIR);

File f = new File(fileName);

channelSftp.put(new FileInputStream(f), f.getName());

log.info(“File transfered successfully to host.”);

} catch (Exception ex) {

System.out.println(“Exception found while tranfer the response.”);

} finally {

channelSftp.exit();

System.out.println(“sftp Channel exited.”);

channel.disconnect();

System.out.println(“Channel disconnected.”);

session.disconnect();

System.out.println(“Host Session disconnected.”);

}

}

Source code from Dhinakar

Download a file.

A similar example of Java code also uses the JSch API to download a file from the SFTP server using “get.”

 

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.io.OutputStream;

import com.jcraft.jsch.Channel;

import com.jcraft.jsch.ChannelSftp;

import com.jcraft.jsch.JSch;

import com.jcraft.jsch.Session;

public static void main(String[] args) {

String SFTPHOST = “host_IP”;

int SFTPPORT = 22;

String SFTPUSER = “username”;

String SFTPPASS = “password”;

String SFTPWORKINGDIR = “/file/to/get”;

Session session = null;

Channel channel = null;

ChannelSftp channelSftp = null;

System.out.println(“preparing the host information for sftp.”);

try {

JSch jsch = new JSch();

session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);

session.setPassword(SFTPPASS);

java.util.Properties config = new java.util.Properties();

config.put(“StrictHostKeyChecking”, “no”);

session.setConfig(config);

session.connect();

System.out.println(“Host connected.”);

channel = session.openChannel(“sftp”);

channel.connect();

System.out.println(“sftp channel opened and connected.”);

channelSftp = (ChannelSftp) channel;

channelSftp.cd(SFTPWORKINGDIR);

byte[] buffer = new byte[1024];

BufferedInputStream bis = new

BufferedInputStream(channelSftp.get(“Test.txt”));

File newFile = new File(“C:/Test.txt”);

OutputStream os = new FileOutputStream(newFile);

BufferedOutputStream bos = new BufferedOutputStream(os);

int readCount;

while ((readCount = bis.read(buffer)) > 0) {

System.out.println(“Writing: “);

bos.write(buffer, 0, readCount);

}

bis.close();

bos.close();

} catch (Exception ex) {

ex.printStackTrace();

}

}

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.

Get a 7-day free trial

Start 7-day Free Trial!

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.

Get a 30-day free trial

Start 30-day Free Trial!

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.