Java Program For Uploading Folder Content recursively from local to SFTP Server

DeeKay December 29, 2016 at 3:55 am · How To, SFTP

Java program for uploading the content of a local machine directory or folder to SFTP server is not straight forward. If we use JSCH API for SFTP upload then you cannot use channelSftp.put(new FileInputStream(sourceFile), sourceFile.getName(), ChannelSftp.OVERWRITE); method. This channelSftp.put() method will work for single file upload but you cannot use it for folder upload.

Below Java program will show you how to upload a directory or folder content from local machine to SFTP server recursively –

<br />
/**<br />
 * Created on Dec 27, 2016 Copyright(c) http://kodehelp.com All Rights Reserved.<br />
 */<br />
package com.kodehelp.sftp;</p>
<p>import java.io.File;<br />
import java.io.FileInputStream;<br />
import java.io.FileNotFoundException;</p>
<p>import com.jcraft.jsch.Channel;<br />
import com.jcraft.jsch.ChannelSftp;<br />
import com.jcraft.jsch.JSch;<br />
import com.jcraft.jsch.Session;<br />
import com.jcraft.jsch.SftpATTRS;<br />
import com.jcraft.jsch.SftpException;</p>
<p>/**<br />
 * @author http://kodehelp.com<br />
 *<br />
 */<br />
public class UploadRecursiveFolderToSFTPServer {</p>
<p>	static ChannelSftp channelSftp = null;<br />
	static Session session = null;<br />
	static Channel channel = null;<br />
	static String PATHSEPARATOR = "/";</p>
<p>	/**<br />
	 * @param args<br />
	 */<br />
	public static void main(String[] args) {<br />
		String SFTPHOST = "10.20.30.40"; // SFTP Host Name or SFTP Host IP Address<br />
		int SFTPPORT = 22; // SFTP Port Number<br />
		String SFTPUSER = "SFTP USERNAME"; // User Name<br />
		String SFTPPASS = "SFTP PASSWORD"; // Password<br />
		String SFTPWORKINGDIR = "/home/kodehelp/upload"; // Source Directory on SFTP server<br />
		String LOCALDIRECTORY = "C:\\temp"; // Local Target Directory</p>
<p>		try {<br />
			JSch jsch = new JSch();<br />
			session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);<br />
			session.setPassword(SFTPPASS);<br />
			java.util.Properties config = new java.util.Properties();<br />
			config.put("StrictHostKeyChecking", "no");<br />
			session.setConfig(config);<br />
			session.connect(); // Create SFTP Session<br />
			channel = session.openChannel("sftp"); // Open SFTP Channel<br />
			channel.connect();<br />
			channelSftp = (ChannelSftp) channel;<br />
			channelSftp.cd(SFTPWORKINGDIR); // Change Directory on SFTP Server</p>
<p>			recursiveFolderUpload(LOCALDIRECTORY,SFTPWORKINGDIR);</p>
<p>		} catch (Exception ex) {<br />
			ex.printStackTrace();<br />
		} finally {<br />
			if (channelSftp != null)<br />
				channelSftp.disconnect();<br />
			if (channel != null)<br />
				channel.disconnect();<br />
			if (session != null)<br />
				session.disconnect();</p>
<p>		}</p>
<p>	}</p>
<p>	/**<br />
	 * This method is called recursively to Upload the local folder content to<br />
	 * SFTP server<br />
	 *<br />
	 * @param sourcePath<br />
	 * @param destinationPath<br />
	 * @throws SftpException<br />
	 * @throws FileNotFoundException<br />
	 */<br />
	private static void recursiveFolderUpload(String sourcePath, String destinationPath) throws SftpException, FileNotFoundException {</p>
<p>		File sourceFile = new File(sourcePath);<br />
		if (sourceFile.isFile()) {</p>
<p>			// copy if it is a file<br />
			channelSftp.cd(destinationPath);<br />
			if (!sourceFile.getName().startsWith("."))<br />
				channelSftp.put(new FileInputStream(sourceFile), sourceFile.getName(), ChannelSftp.OVERWRITE);</p>
<p>		} else {</p>
<p>			System.out.println("inside else " + sourceFile.getName());<br />
			File[] files = sourceFile.listFiles();</p>
<p>			if (files != null &amp;&amp; !sourceFile.getName().startsWith(".")) {</p>
<p>				channelSftp.cd(destinationPath);<br />
				SftpATTRS attrs = null;</p>
<p>				// check if the directory is already existing<br />
				try {<br />
					attrs = channelSftp.stat(destinationPath + "/" + sourceFile.getName());<br />
				} catch (Exception e) {<br />
					System.out.println(destinationPath + "/" + sourceFile.getName() + " not found");<br />
				}</p>
<p>				// else create a directory<br />
				if (attrs != null) {<br />
					System.out.println("Directory exists IsDir=" + attrs.isDir());<br />
				} else {<br />
					System.out.println("Creating dir " + sourceFile.getName());<br />
					channelSftp.mkdir(sourceFile.getName());<br />
				}</p>
<p>				for (File f: files) {<br />
					recursiveFolderUpload(f.getAbsolutePath(), destinationPath + "/" + sourceFile.getName());<br />
				}</p>
<p>			}<br />
		}</p>
<p>	}</p>
<p>}</p>
<p>