HomeHow-ToHow to Transfer file through SFTP in Java

How to Transfer file through SFTP in Java

In this journal entry, we will be looking at the methods on how to transfer a file through SFTP in Java on a remote server. The main point of focus is basically uploading and downloading the files from a remote server using SFTP.

We will be using two different libraries which help in transferring the files: JSch and Apache Commons VFS

Using JSch

Let’s first have a look at the JSch library for uploading and downloading the files from a remote server.

Maven Configuration

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>

To get a particular version or the latest version of JSch, please head over to the Maven Repository.

Configuring JSch

We will be setting up the JSch using password authentication although this library also provides support for Public Key authentication.

private String hostName = "HOST_NAME_HERE";
private String userName = "USERNAME_HERE";
private String password = "PASSWORD_HERE";
private int portNumber = PORT_NUMBER;

public ChannelSftp configureSftp() throws JSchException {
	JSch jsch = new JSch();
	Session session = jsch.getSession(userName, hostName, portNumber);
        jsch.setKnownHosts("/Users/DevelopersJournal/.ssh/known_hosts");
	session.setPassword(password);
	session.connect();

	return (ChannelSftp) session.openChannel("sftp");
}

The known_hosts file can be generated using the following command:

ssh-keyscan -H -t rsa REMOTE_HOSTNAME >> known_hosts

Uploading a File – JSch

Now that we have created the configuration method for JSch, let’s have a look at how we are going to upload files using the above configuration.

public void uploadFileUsingJSch() throws JSchException, SftpException {
    ChannelSftp channelSftp = configureSftp();
    channelSftp.connect();
  
    String localFile = "src/main/resources/fileToUpload.txt";
    String remoteDir = "remote_sftp_dir/";
  
    channelSftp.put(localFile, remoteDir + "jschFileUploaded.txt");
  
    channelSftp.exit();
}

The ChannelSftp provides the method put to upload the files on the server. The first parameter of the method represents the local file that needs to be transferred on the remote server, for example, src/main/resources/fileToUpload.txt, while remoteDir is the path of the target directory at the remote server.

Downloading a File – JSch

Its time to download the file which were uploaded or exists on the remote server.

public void downloadFileUsingJsch() throws JSchException, SftpException {
    ChannelSftp channelSftp = configureJsch();
    channelSftp.connect();
  
    String remoteFile = "fileToDownload.txt";
    String localDir = "src/main/resources/";
  
    channelSftp.get(remoteFile, localDir + "jschFileDownloaded.txt");
  
    channelSftp.exit();
}

The remoteFile variable defined specifies the file that needs to be downloaded, and localDir represents the path of the target local directory.

Using Apache Commons VFS

Now we will be looking at another library for uploading and downloading the files from the remote server in a Java application. Internally the Apache Commons VFS uses the JSch library.

Maven Configuration

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-vfs2</artifactId>
    <version>2.4.1</version>
</dependency>

To get a particular version or the latest version of Apache Commons VFS, please head over to the Maven Repository.

Uploading a File – Apache Commons VFS

Apache Commons VFS works in a little different way. It uses a FileSystemManager to create FileObjects from the target files, then it uses this FileObjects to transfer/upload the files.

In the below example, we’ll be uploading the file by using method FileObject.copyFrom().

public void uploadFileUsingVfs() throws IOException {
    FileSystemManager fsManager = VFS.getManager();
  
    FileObject localObject = fsManager.resolveFile(
      System.getProperty("user.dir") + "/" + localFile);
    FileObject remoteObject = fsManager.resolveFile(
      "sftp://" + userName + ":" + password + "@" + remoteHost + "/" + remoteDir + "vfsFileUpload.txt");
  
    remoteObject.copyFrom(localObject, Selectors.SELECT_SELF);
  
    localObject.close();
    remoteObject.close();
}

A point to note here is that the localObject file path should be absolute, and the remoteObject file path should start with sftp://userName:password@remoteHost.

Downloading a File – Apache Commons VFS

Downloading a file from a remote server is very similar — we’ll use the same FileObject.copyFrom() to copy from remote server.

public void downloadFileUsingVfs() throws IOException {
	String localDir = "downloads/";
    FileSystemManager fsManager = VFS.getManager();
  
    FileObject localObject = fsManager.resolveFile(
      System.getProperty("user.dir") + "/" + localDir + "vfsFileDownload.txt");
    FileObject remoteObject = fsManager.resolveFile(
      "sftp://" + userName + ":" + password + "@" + remoteHost + "/" + remoteFile);
  
    localObject.copyFrom(remoteObject, Selectors.SELECT_SELF);
  
    localObject.close();
    remoteObject.close();
}

Conclusion

In this journal entry, we tried to learn how to upload and download files from a remote SFTP server in Java. For this, we used two different libraries: JSch and Apache Commons VFS.

RELATED ARTICLES

Most Popular