Sample code for 30+ languages & platforms
Java

Remove a Remote Directory on an SFTP Server

See more SFTP Examples

Demonstrates the Chilkat SFtp.RemoveDir method, which deletes a remote directory. The only argument is the directory path.

Background: Most SFTP servers refuse to remove a directory that is not empty, so deleting a populated tree means removing its files and subdirectories first — the inverse of building a path level by level. There is no single "recursive delete" in the SFTP protocol; a client implements it by listing, descending, and removing bottom-up.

Chilkat Java Downloads

Java
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    //  Demonstrates the SFtp.RemoveDir method, which deletes a remote directory.  The only argument
    //  is the directory path.

    CkSFtp sftp = new CkSFtp();

    //  Connect, authenticate, and initialize the SFTP subsystem.
    int port = 22;
    success = sftp.Connect("sftp.example.com",port);
    if (success == false) {
        System.out.println(sftp.lastErrorText());
        return;
        }

    //  Normally you would not hard-code the password in source.  You should instead obtain it
    //  from an interactive prompt, environment variable, or a secrets vault.
    String password = "mySshPassword";

    success = sftp.AuthenticatePw("mySshLogin",password);
    if (success == false) {
        System.out.println(sftp.lastErrorText());
        return;
        }

    success = sftp.InitializeSftp();
    if (success == false) {
        System.out.println(sftp.lastErrorText());
        return;
        }

    //  Delete a remote directory.  Most SFTP servers require the directory to be empty first.
    success = sftp.RemoveDir("subdir/oldfolder");
    if (success == false) {
        System.out.println(sftp.lastErrorText());
        return;
        }

    System.out.println("Directory removed.");

    sftp.Disconnect();
  }
}