Skip to content

Instantly share code, notes, and snippets.

@olieidel
Last active June 4, 2023 16:12
Show Gist options
  • Save olieidel/c551a911a4798312e4ef42a584677397 to your computer and use it in GitHub Desktop.
Save olieidel/c551a911a4798312e4ef42a584677397 to your computer and use it in GitHub Desktop.
Delete Directories recursively with Clojure in only 4 lines of code.
(ns yourproject.yourns
(:require [clojure.java.io :as io]))
(defn delete-directory-recursive
"Recursively delete a directory."
[^java.io.File file]
;; when `file` is a directory, list its entries and call this
;; function with each entry. can't `recur` here as it's not a tail
;; position, sadly. could cause a stack overflow for many entries?
;; thanks to @nikolavojicic for the idea to use `run!` instead of
;; `doseq` :)
(when (.isDirectory file)
(run! delete-directory-recursive (.listFiles file)))
;; delete the file or directory. if it it's a file, it's easily
;; deletable. if it's a directory, we already have deleted all its
;; contents with the code above (remember?)
(io/delete-file file))
@nikolavojicic
Copy link

nikolavojicic commented Nov 9, 2021

Even shorter :)

(run! delete-directory-recursive (.listFiles file))

...instead of doseq...

@olieidel
Copy link
Author

Great point, I didn't even know about run!. Thanks, edited!

@kmrozek-shareablee
Copy link

That one line should work too:

(run! io/delete-file (reverse (file-seq file)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment