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:

 

(174 Posts)

20 years of coding and working as software engineer but I am still eager to learn more. I am very passionate when it comes to open source, Linux and Java. But I made my peace with Windows long ago to fully enjoy my PC gaming hobby. I have a soft spot for 90s electronic music and Babylon 5. In the evenings you will find me roaming the endless space in Warframe (IGN k05h).

3 thoughts on “Recursively delete directory with JSch on SFTP with Java

  1. Pingback: 【规避解决】sftp中rmdir出错:Couldn’t remove directory: Failure – 在路上

  2. Vladislav

    You also can add something like it to your code

    BiConsumer removesSftp = (clouser, path) -> {
    try {
    clouser.call(path);
    } catch (Exception e) {
    if (!(e instanceof SftpException) || ((SftpException) e).id != 2) {//no such file code
    throw new RuntimeException(e);
    }
    }
    };

    removesSftp.accept(channelSftp::rm, "1.txt");
    removesSftp.accept(channelSftp::rmdir, "a/");

    1. Lars Händler

      Oh, I havent thought of lamda expression for this problem. I will give it a try in my next code cleanup. It looks so fancy!

Comments are closed.