Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing files in a directory in Clojure

Tags:

java

clojure

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?

like image 868
Mike Crittenden Avatar asked Dec 19 '11 19:12

Mike Crittenden


2 Answers

Use file-seq function.

Usage example:

(def directory (clojure.java.io/file "/path/to/directory")) (def files (file-seq directory)) (take 10 files) 
like image 175
ffriend Avatar answered Sep 23 '22 19:09

ffriend


Clojure was designed to embrace the Java platform, and this is one area where Clojure does not provide its own API. This means that you probably have to dive into Java, but the classes you have to work with are perfectly usable directly from Clojure.

The one class you should read about in the javadocs is java.io.File, which represents a file path.

http://docs.oracle.com/javase/6/docs/api/java/io/File.html

The .listFiles instance method returns an array (which you can use as a seq) of File objects – one for each entry in the directory identified by the File instance. There are other useful methods for determining whether a File exists, is a directory, and so on.

Example

(ns my-file-utils   (:import java.io.File))  (defn my-ls [d]   (println "Files in " (.getName d))   (doseq [f (.listFiles d)]     (if (.isDirectory f)       (print "d ")       (print "- "))     (println (.getName f))))  ;; Usage: (my-ls (File. ".")) 

Constructing File Objects

The constructor of File can sometimes be a bit inconvenient to use (especially when merging many path segments in one go) and in this case Clojure provides a useful helper function: clojure.java.io/file. As its arguments it accepts path segments as strings or files. The segments are joined with the correct path separator of the platform.

http://clojuredocs.org/clojure_core/clojure.java.io/file

Note: Clojure also provides the file-seq function which returns a preorder walk (as a seq) though the file hierarchy starting at the given file.

like image 24
raek Avatar answered Sep 25 '22 19:09

raek