How to delete folder recursively on remote server using SFTP in java?

DeeKay January 5, 2017 at 3:46 am · How To, SFTP

Deleting or removing a folder recursively on the remote server in java is easy using JSCH (SFTP) API. Nowadays it is a common use case in software projects where you need to delete or remove a folder from the remote server using SFTP connection.

Below java code shows you how you can delete or remove a folder recursively from the remote server using SFTP connection in java code.

 

<br />
/**<br />
 * Created on Jan 4, 2017 Copyright(c) https://kodehelp.com All Rights Reserved.<br />
 */<br />
package com.kodehelp.sftp;</p>
<p>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 https://kodehelp.com<br />
 *<br />
 */<br />
public class DeleteFolderFromSFTPServer {</p>
<p>	static Session session = null;<br />
	static Channel channel = null;<br />
	static ChannelSftp channelSftp = null;</p>
<p>	public static void main(String[] args) {</p>
<p>		String SFTPHOST = "10.20.30.40"; // SFTP Host Name or SFTP Host IP Address<br />
		int SFTPPORT = 22; // SFTP Port Number<br />
		String SFTPUSER = "SFTPUSER"; // User Name<br />
		String SFTPPASS = "SFTP Password"; // Password<br />
		String SFTPWORKINGDIR = "/home/kodehelp/temp"; // Source Directory on SFTP server in which the file is located on remote server<br />
		boolean deletedflag = false;</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;</p>
<p>			recursiveFolderDelete(SFTPWORKINGDIR);</p>
<p>			deletedflag = true;<br />
			if(deletedflag)<br />
				System.out.println("folder deleted");</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>	@SuppressWarnings("unchecked")<br />
	private static void recursiveFolderDelete(String path) throws SftpException {</p>
<p>		channelSftp.cd(path); // Change Directory on SFTP Server<br />
		// List source directory structure.<br />
		Vector&amp;amp;amp;amp;amp;amp;lt;ChannelSftp.LsEntry&amp;amp;amp;amp;amp;amp;gt; fileAndFolderList = channelSftp.ls(path); </p>
<p>		// Iterate objects in the list to get file/folder names.<br />
	    for (ChannelSftp.LsEntry item : fileAndFolderList) { </p>
<p>	    	// If it is a file (not a directory).<br />
	        if (!item.getAttrs().isDir()) {</p>
<p>	            channelSftp.rm(path + "/" + item.getFilename()); // Remove file.</p>
<p>	        } else if (!(".".equals(item.getFilename()) || "..".equals(item.getFilename()))) { // If it is a subdir.</p>
<p>	            try {</p>
<p>	            	// removing sub directory.<br />
	                channelSftp.rmdir(path + "/" + item.getFilename()); </p>
<p>	            } catch (Exception e) { // If subdir is not empty and error occurs.</p>
<p>	            	// Do lsFolderRemove on this subdir to enter it and clear its contents.<br />
	            	recursiveFolderDelete(path + "/" + item.getFilename());<br />
	            }<br />
	        }<br />
	    }</p>
<p>	    channelSftp.rmdir(path); // delete the parent directory after empty</p>
<p>	}</p>
<p>}</p>
<p>