Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Recursively delete directory with JSch on SFTP with Java

For a recent project I needed a way to recursively delete a directory and all its content from a remote SFTP connection. This code snippet works like charm but be very careful when using it:

/**
 * Delete a SFTP directory including ALL its content
 * "With great power comes great responsibility"
 * 
 * @param remoteDir
 */
public void recursiveDirectoryDelete(String remoteDir)
{
	try
	{
		if(isDirectory(remoteDir))
		{
			Vector<ChannelSftp.LsEntry> dirList = sftpChannel.ls(remoteDir);
			
			for(ChannelSftp.LsEntry entry : dirList)
			{
				if(!(entry.getFilename().equals(".") || entry.getFilename().equals("..")))
				{
					if(entry.getAttrs().isDir())
					{
						recursiveDirectoryDelete(remoteDir + entry.getFilename() + File.separator);
					}
					else
					{
						sftpChannel.rm(remoteDir + entry.getFilename());
					}
				}
			}

			sftpChannel.cd("..");
			sftpChannel.rmdir(remoteDir);
		}
	}
	catch (SftpException e)
	{
		logger.warn(e.getMessage());
	}
}	


private boolean isDirectory(String remoteDirectory) throws SftpException
{
	return sftpChannel.stat(remoteDirectory).isDir();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.