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:

 

 

(172 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).

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

  1. 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/");

    Reply
    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!

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *