How can I create a list out of all of the files in a specific directory in Clojure? Do I have to resort to calling Java or can Clojure handle this natively?
A macro to take care of list the files in directory - recursively or just in the parent directory. It can also search files with specific ending extension.
;; lists all the files recursively inside the directory passed as d like "."
(defmacro my-rec-list
"generate the recursive list" {:added "1.0"}
[d str rec]
`(->> ~d
clojure.java.io/file
~(if (= rec "rec")
`file-seq
`(.listFiles))
~(cond
(= str "file") `(filter #(.isFile %))
(= str "dir") `(filter #(.isDirectory %))
:always `(filter #(.matches (.getPathMatcher
(java.nio.file.FileSystems/getDefault)
~str) (.getFileName (.toPath %)))))
(mapv #(.getAbsolutePath %))))
(defn my-rec-ls-file
"generate the recursive list for only files in a directory"
[d ]
(my-rec-list d "file" "rec"))
(defn my-rec-ls-dir
"generate the recursive list for only directory"
[d ]
(my-rec-list d "dir" "rec"))
(defn my-rec-ls-jpg
"generate the recursive list for files and directory"
[d ]
(my-rec-list d "glob:*.jpg" "rec"))
(defn my-ls-file
"generate the recursive list for only files in a directory"
[d ]
(my-rec-list d "file" "norec"))
(defn my-ls-dir
"generate the recursive list for only directory"
[d ]
(my-rec-list d "dir" "norec"))
(defn my-ls-jpg
"generate the recursive list for files and directory"
[d ]
(my-rec-list d "glob:*.jpg" "norec"))
It leads to different function which can be called with directory to get the list of files, directory or matching extension file - recursively or non-recursively. Example is -
(def directory (clojure.java.io/file "/Path/to/Directory"))
(my-rec-ls-jpg directory) ;; find all jpg file recessively in directory
(my-ls-jpg directory) ;; find jpg file in current directory