I\'d like to know the \"recommended\" way of reading and writing a file in clojure 1.3 .
If the file fits into memory you can read and write it with slurp and spit:
(def s (slurp "filename.txt"))
(s now contains the content of a file as a string)
(spit "newfile.txt" s)
This creates newfile.txt if it doesnt exit and writes the file content. If you want to append to the file you can do
(spit "filename.txt" s :append true)
To read or write a file linewise you would use Java's reader and writer. They are wrapped in the namespace clojure.java.io:
(ns file.test
(:require [clojure.java.io :as io]))
(let [wrtr (io/writer "test.txt")]
(.write wrtr "hello, world!\n")
(.close wrtr))
(let [wrtr (io/writer "test.txt" :append true)]
(.write wrtr "hello again!")
(.close wrtr))
(let [rdr (io/reader "test.txt")]
(println (.readLine rdr))
(println (.readLine rdr)))
; "hello, world!"
; "hello again!"
Note that the difference between slurp/spit and the reader/writer examples is that the file remains open (in the let statements) in the latter and the reading and writing is buffered, thus more efficient when repeatedly reading from / writing to a file.
Here is more information: slurp spit clojure.java.io Java's BufferedReader Java's Writer