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.

 

/**
 * Created on Jan 4, 2017 Copyright(c) https://kodehelp.com All Rights Reserved.
 */
package com.kodehelp.sftp;

import java.util.Vector;

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

/**
 * @author https://kodehelp.com
 *
 */
public class DeleteFolderFromSFTPServer {
	
	static Session session = null;
	static Channel channel = null;
	static ChannelSftp channelSftp = null;
	
	public static void main(String[] args) {
		
		String SFTPHOST = "10.20.30.40"; // SFTP Host Name or SFTP Host IP Address
		int SFTPPORT = 22; // SFTP Port Number
		String SFTPUSER = "SFTPUSER"; // User Name
		String SFTPPASS = "SFTP Password"; // Password
		String SFTPWORKINGDIR = "/home/kodehelp/temp"; // Source Directory on SFTP server in which the file is located on remote server
		boolean deletedflag = false;

		try {
			JSch jsch = new JSch();
			session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
			session.setPassword(SFTPPASS);
			java.util.Properties config = new java.util.Properties();
			config.put("StrictHostKeyChecking", "no");
			session.setConfig(config);
			session.connect(); // Create SFTP Session
			channel = session.openChannel("sftp"); // Open SFTP Channel
			channel.connect();
			channelSftp = (ChannelSftp) channel;
			
			
			recursiveFolderDelete(SFTPWORKINGDIR);
			
			
			deletedflag = true;
			if(deletedflag)
				System.out.println("folder deleted");
			
			
			
			
		}catch(Exception ex){
			ex.printStackTrace();
		}finally {
			if (channelSftp != null)
				channelSftp.disconnect();
			if (channel != null)
				channel.disconnect();
			if (session != null)
				session.disconnect();

		}
		
		

	}
	
	@SuppressWarnings("unchecked")
	private static void recursiveFolderDelete(String path) throws SftpException {
		
		channelSftp.cd(path); // Change Directory on SFTP Server
		// List source directory structure.
		Vector<ChannelSftp.LsEntry> fileAndFolderList = channelSftp.ls(path); 
		
		// Iterate objects in the list to get file/folder names.
	    for (ChannelSftp.LsEntry item : fileAndFolderList) { 
	    	
	    	// If it is a file (not a directory).
	        if (!item.getAttrs().isDir()) {
	        	
	            channelSftp.rm(path + "/" + item.getFilename()); // Remove file.
	            
	        } else if (!(".".equals(item.getFilename()) || "..".equals(item.getFilename()))) { // If it is a subdir.
	        	
	            try {
	            	
	            	// removing sub directory.
	                channelSftp.rmdir(path + "/" + item.getFilename()); 
	                
	            } catch (Exception e) { // If subdir is not empty and error occurs.
	            	
	            	// Do lsFolderRemove on this subdir to enter it and clear its contents.
	            	recursiveFolderDelete(path + "/" + item.getFilename()); 
	            }
	        }
	    }
	    
	    channelSftp.rmdir(path); // delete the parent directory after empty
		
	}

}