Java Program For Downloading Folder Content recursively from SFTP Server

DeeKay December 28, 2016 at 4:56 am · How To, SFTP

How to download folder from SFTP Server (Secure File Transfer Protocol) is the common use case for Java developer who wants to download folder from SFTP. To write a java program to download from SFTP, you will need to download JSCH jar file.

For other SFTP operations in java, please refer below posts on Kodehelp.com –

Below Java program is for downloading folder/directory content recursively from SFTP server.

 

<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.util.Vector;</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.SftpException;</p>
<p>/**<br />
 * @author http://kodehelp.com<br />
 *<br />
 */<br />
public class DownloadRecursiveFolderFromSFTP {</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 = "SFTPUserName"; // User Name<br />
		String SFTPPASS = "SFTPPassword"; // Password<br />
		String SFTPWORKINGDIR = "/home/kodehelp/download"; // 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>			recursiveFolderDownload(SFTPWORKINGDIR, LOCALDIRECTORY); // Recursive folder content download from SFTP server</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 download the folder content from SFTP server<br />
	 *<br />
	 * @param sourcePath<br />
	 * @param destinationPath<br />
	 * @throws SftpException<br />
	 */<br />
	@SuppressWarnings("unchecked")<br />
	private static void recursiveFolderDownload(String sourcePath, String destinationPath) throws SftpException {<br />
		Vector<ChannelSftp.LsEntry> fileAndFolderList = channelSftp.ls(sourcePath); // Let list of folder content</p>
<p>		//Iterate through list of folder content<br />
		for (ChannelSftp.LsEntry item : fileAndFolderList) {</p>
<p>			if (!item.getAttrs().isDir()) { // Check if it is a file (not a directory).<br />
				if (!(new File(destinationPath + PATHSEPARATOR + item.getFilename())).exists()<br />
						|| (item.getAttrs().getMTime() > Long<br />
								.valueOf(new File(destinationPath + PATHSEPARATOR + item.getFilename()).lastModified()<br />
										/ (long) 1000)<br />
								.intValue())) { // Download only if changed later.</p>
<p>					new File(destinationPath + PATHSEPARATOR + item.getFilename());<br />
					channelSftp.get(sourcePath + PATHSEPARATOR + item.getFilename(),<br />
							destinationPath + PATHSEPARATOR + item.getFilename()); // Download file from source (source filename, destination filename).<br />
				}<br />
			} else if (!(".".equals(item.getFilename()) || "..".equals(item.getFilename()))) {<br />
				new File(destinationPath + PATHSEPARATOR + item.getFilename()).mkdirs(); // Empty folder copy.<br />
				recursiveFolderDownload(sourcePath + PATHSEPARATOR + item.getFilename(),<br />
						destinationPath + PATHSEPARATOR + item.getFilename()); // Enter found folder on server to read its contents and create locally.<br />
			}<br />
		}<br />
	}</p>
<p>}<br />