Transfer files from one remote server to another using Java

Previously, we discussed transferring files from local machines to remote servers, and this post will focus on copying or transferring files between remote servers.

We will use the JSch library to connect and transfer the files from one remote server to another.

To transfer files, we will proceed with the following steps –

Let’s look at the above steps one by one.

Add Jsch dependency in the pom.xml file

Add the below dependency in your pom.xml file

<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>
Connect to the remote servers

We have created a separate post detailing the process of connecting to a remote server. Below, we have provided the code snippet to facilitate server connection.

	public Session connect(String username, String password, String host, int port, String FILE_KEY_NAME) {
		Session session = null;
		try {

			JSch jsch = new JSch();

			// if there is a key, then connect using that key
			// otherwise, we will connect using a password
			if (FILE_KEY_NAME != null && !FILE_KEY_NAME.equals("")) {
				jsch.addIdentity(FILE_KEY_NAME);
				session = jsch.getSession(username, host, port);
			} else {
				session = jsch.getSession(username, host, port);
				session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
				session.setPassword(password);
			}

			session.setConfig("StrictHostKeyChecking", "no");
			session.setTimeout(15000);
			session.connect();

			System.out.println("Connected to: " + host);
			return session;
		} catch (JSchException e) {
			e.printStackTrace();
			session.disconnect();
			return null;
		}

	}

Let’s establish connections with the servers at 127.0.0.1 and 127.0.0.2. We will then transfer a file from 127.0.0.1 to 127.0.0.2.

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class CodekruTransferFiles {

	public static void main(String[] args) {

		CodekruTransferFiles codekruTransferFiles = new CodekruTransferFiles();

		String sourceHost = "127.0.0.1";
		String sourceUsername = "codekru1";
		String sourcePassword = "codekru1";

		String targerHost = "127.0.0.2";
		String targetUsername = "codekru2";
		String targetPassword = "codekru2";

		try {

			Session sourceSession = codekruTransferFiles.connect(sourceUsername, sourcePassword, sourceHost, 22, null);
			Session targetSession = codekruTransferFiles.connect(targetUsername, targetPassword, targerHost, 22, null);

			// Open SFTP channels for both source and target servers
			ChannelSftp sourceChannel = (ChannelSftp) sourceSession.openChannel("sftp");
			sourceChannel.connect();

			ChannelSftp targetChannel = (ChannelSftp) targetSession.openChannel("sftp");
			targetChannel.connect();

			// Disconnect and close channels
			sourceChannel.disconnect();
			targetChannel.disconnect();

			// Disconnect SSH sessions
			sourceSession.disconnect();
			targetSession.disconnect();

		} catch (JSchException e) {
			e.printStackTrace();
		}
	}

	public Session connect(String username, String password, String host, int port, String FILE_KEY_NAME) {
		Session session = null;
		try {

			JSch jsch = new JSch();

			// if there is a key, then connect using that key
			// otherwise, we will connect using a password
			if (FILE_KEY_NAME != null && !FILE_KEY_NAME.equals("")) {
				jsch.addIdentity(FILE_KEY_NAME);
				session = jsch.getSession(username, host, port);
			} else {
				session = jsch.getSession(username, host, port);
				session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
				session.setPassword(password);
			}

			session.setConfig("StrictHostKeyChecking", "no");
			session.setTimeout(15000);
			session.connect();

			System.out.println("Connected to: " + host);
			return session;
		} catch (JSchException e) {
			e.printStackTrace();
			session.disconnect();
			return null;
		}

	}

}

We have used passwords to connect with our remote servers, alternatively, you can also use a key to connect with them.

Transfer files

The below code will transfer the codekru.txt file from 127.0.0.1 to 127.0.0.2.

		String sourceFilePath = "/usr/workspace/codekru.txt";
		String targetFilePath = "/usr/workspace/codekru.txt";			

        // Get an InputStream from the source file and put it directly to target server
			try (InputStream inputStream = sourceChannel.get(sourceFilePath);
					OutputStream outputStream = targetChannel.put(targetFilePath)) {
				byte[] buffer = new byte[1024];
				int bytesRead;
				while ((bytesRead = inputStream.read(buffer)) != -1) {
					outputStream.write(buffer, 0, bytesRead);
				}
			}

Let’s go through the code –

  • try (InputStream inputStream = sourceChannel.get(sourceFilePath);
    OutputStream outputStream = targetChannel.put(targetFilePath)) – This is a try-with-resources block that automatically manages closing resources, saving us the effort of writing code to close files after use.
  • InputStream inputStream = sourceChannel.get(sourceFilePath); – This retrieves an input stream to read the contents of the source file located at sourceFilePath. The get() method is used to initiate the transfer of the source file.
  • OutputStream outputStream = targetChannel.put(targetFilePath); – This retrieves an OutputStream to write the contents to the target file located at targetFilePath. The put() method is used to initiate the transfer to the target file.
  • outputStream.write(buffer, 0, bytesRead);: This line writes the contents of the buffer to the OutputStream. It writes only the number of bytes that were read in the current iteration, which is specified by the bytesRead value.
  • The loop continues to read data from the source and write it to the target until the read() method returns -1, indicating that there are no more data to read from the source. At this point, the transfer is complete.

Here is the whole code for transferring a file ( codekru.txt ) from one server (127.0.0.1) to another (127.0.0.2).

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class CodekruTransferFiles {

	public static void main(String[] args) throws IOException {

		CodekruTransferFiles codekruTransferFiles = new CodekruTransferFiles();

		String sourceHost = "127.0.0.1";
		String sourceUsername = "codekru1";
		String sourcePassword = "codekru1";

		String targerHost = "127.0.0.2";
		String targetUsername = "codekru2";
		String targetPassword = "codekru2";

		String sourceFilePath = "/usr/workspace/codekru.txt";
		String targetFilePath = "/usr/workspace/codekru.txt";

		try {

			Session sourceSession = codekruTransferFiles.connect(sourceUsername, sourcePassword, sourceHost, 22, null);
			Session targetSession = codekruTransferFiles.connect(targetUsername, targetPassword, targerHost, 22, null);

			// Open SFTP channels for both source and target servers
			ChannelSftp sourceChannel = (ChannelSftp) sourceSession.openChannel("sftp");
			sourceChannel.connect();

			ChannelSftp targetChannel = (ChannelSftp) targetSession.openChannel("sftp");
			targetChannel.connect();

			System.out.println("Starting the transference of file...");

			// Get an InputStream from the source file and put it directly to target server
			try (InputStream inputStream = sourceChannel.get(sourceFilePath);
					OutputStream outputStream = targetChannel.put(targetFilePath)) {
				byte[] buffer = new byte[1024];
				int bytesRead;
				while ((bytesRead = inputStream.read(buffer)) != -1) {
					outputStream.write(buffer, 0, bytesRead);
				}
			}

			// Disconnect and close channels
			sourceChannel.disconnect();
			targetChannel.disconnect();

			// Disconnect SSH sessions
			sourceSession.disconnect();
			targetSession.disconnect();

			System.out.println("File transfer successful!");
		} catch (JSchException | SftpException e) {
			e.printStackTrace();
		}
	}

	public Session connect(String username, String password, String host, int port, String FILE_KEY_NAME) {
		Session session = null;
		try {

			JSch jsch = new JSch();

			// if there is a key, then connect using that key
			// otherwise, we will connect using a password
			if (FILE_KEY_NAME != null && !FILE_KEY_NAME.equals("")) {
				jsch.addIdentity(FILE_KEY_NAME);
				session = jsch.getSession(username, host, port);
			} else {
				session = jsch.getSession(username, host, port);
				session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
				session.setPassword(password);
			}

			session.setConfig("StrictHostKeyChecking", "no");
			session.setTimeout(15000);
			session.connect();

			System.out.println("Connected to: " + host);
			return session;
		} catch (JSchException e) {
			e.printStackTrace();
			session.disconnect();
			return null;
		}

	}

}

We hope that you have liked the article. If you have any doubts or concerns, please write to us in the comments or mail us at admin@codekru.com.

Related Articles –
Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *