Some Practical Clojure Examples
← prev | next →     Top-level ToC     /files-and-directories.html     (printable version)
(require '[ :as io])
(require '[me.raynes.fs    :as fs])

(let [content (slurp "foo.txt")]

(spit "bar.txt"
      "a long string")

(io/reader   "foo.txt")  ;=>
(io/file     "foo.txt")  ;=>
(io/resource "foo.txt")  ;=>

(with-open [rdr (io/reader "foo.txt")]

;; Though in some cases you can just use:
(let [lines (line-seq (io/reader "foo.txt"))]

(file-seq (io/file "."))  ; gives you a seq of object.

(with-open [wrtr (io/writer "bar.txt")]
  (doseq [i my-vec]
    (.write wrtr (str i "\n"))))

(def my-file (io/file "baz.txt"))  ; A object.

(.exists      (io/file "foo.txt"))
(.isDirectory (io/file "path/to/somewhere"))

Some methods (called like (.getFoo (io/file "bar.txt"))):

Method Description
exists Does the file exist?
isDirectory Is the File object a directory?
getName The basename of the file.
getParent The dirname of the file.
getPath Filename with directory.
getAbsolutePath /path/to/the/file.txt
getCanonicalPath like abs path, 1
mkdir Create this directory on disk.
(.listFiles (io/file "path/to/some-dir"))  ; list of File objects
(.list      (io/file "path/to/some-dir"))  ; list of strings

1 fs

Using me.raynes/fs:

(fs/glob "*.txt")  ; returns a seq of File objects
fs/*cwd*           ; fs manages this dynamic var.

;; Most of the me.raynes/fs functions take a string arg.
(fs/exists?   "foo.clj")
(fs/mod-time  "foo.clj")  ; last-modified time
(fs/readable? "foo.clj")
(fs/parent    "foo.clj")  ; The dir foo.clj is in (

(fs/iterate-dir ".") ; root, dirs, files (see below)

;; Calls some func on every 3-element vec in the output
;; of fs/iterate-dir.
(fs/walk ".")

fs/iterate-dir works like Python’s os.walk, giving you root, dirs, and files for each directory here and below (though, note that “root” is a Java file object, while dirs and files are lists of strings). It returns you one big data structure.

See the fs API docs for more.

2 Copying and Deleting

(io/copy (io/file "foo.txt")
         (io/file "foo.txt.bkup"))

;; or
(fs/copy "foo.txt" "foo.txt.bkup")

(io/delete-file "foo.txt")

3 Read a config file

  (slurp (str (System/getenv "HOME")
              (System/getProperty "file.separator")

4 Temporary Files

(import '
(def tmp-file (File/createTempFile "foo" ".txt"))

(with-open [w (io/writer tmp-file)]
  (binding [*out* w]
    (println "some content!")))

Thanks Clojure Cookbook recipe 4.10.

5 See Also

Apache Commons IO (particularly the FilenameUtils class)

  1. Like absolute path, but removes stuff like “/./”, and resolves symlinks.