Read a file using Clojure

I’ve modified the post, the best way to read files is to use the clojure.java.io rather than the contrib duck streams

(use '[clojure.java.io :only (reader)])
(line-seq (reader "/Users/biomunky/.emacs"))

If you are going to do it like this wrap the code in a with-open, like so

(with-open [rdr (reader "file")]
   (println (line-seq rdr)))

if you enter the above code into the REPL, change “file” to point to something on your machine and hit enter you should see the content of the file. The with-open (clojuredocs) makes sure that the files you access are closed properly.

If you aren’t aware of clojuredocs yet visit the site here – the examples are very handy.

— OLDER, BUT WORK —

To read a file with clojure use the duck-streams library from clojure.contrib. The first method uses the read-lines function. It can be imported as follows:

(use '[clojure.contrib.duck-streams ] )
; or import only the read macros
(use '[clojure.contrib.duck-streams :only (read-lines)])

then to read a file:

(read-lines ".emacs")

In the REPL this will dump your data. If you want to dump the content of the file from a script you will need to wrap (println) around the statement.

If you want to take a java-esq approach, using buffered reader, you would have had to do it like this:

(import '(java.io BufferedReader FileReader))
(def br ( new BufferedReader (new FileReader "/Users/biomunky/.emacs")))
(println (line-seq br))
Advertisements

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s