Monday, March 15, 2010

Read a file in clojure

Ok, I have tried quite a bit, and failed to figure out on my own how to read a file. I did come close to doing it, but the solution was throwing a NullPointerException, and the code was not LISPy.

Now, in most other languages, a quick search will yield tons of examples on how to read a file. But for clojure, the information is surprisingly hard to come by!

Luckily, after 3 days of trying to figure it out and looking on the web, I came upon a nice solution at Irrational Exuberance. Thank you, Will Larson, for the excellent page! I wish it would somehow show up a little earlier in a google search - woulda saved me a lot of time.

What I have learned from the above site is shown below.

It is easy (after you are shown how) to read an entire file into memory. Use the slurp function:

user=> (slurp "c:/clojure-1.1.0/.gitignore")
"classes/*\n*jar\npom.xml\nclojure.iws\nclojure.ipr\nnbproject/private/\n*.zip\ndist\n"

For larger files:

C:\clojure-1.1.0>java -cp clojure.jar clojure.main
Clojure 1.1.0
user=>
; import the necessary readers.
; set the namespace to "tokenize"
; Note: setting the namespace also changes the prompt
(ns tokenize
(:import (java.io BufferedReader FileReader)))
java.io.FileReader

tokenize=>
; and this is how its done.
; the line-seq function "Returns the lines of text from rdr as a lazy sequence of strings."
(with-open [rdr (BufferedReader. (FileReader. "c:/clojure-1.1.0/.gitignore"))]
(doseq [line (line-seq rdr)] (println line))
)
**********file contents***********
classes/*
*jar
pom.xml
clojure.iws
clojure.ipr
nbproject/private/
*.zip
dist
**********file contents***********
nil
; Control-Z (in Windows) to exit REPL
tokenize=> ^Z


C:\clojure-1.1.0>

No comments:

Post a Comment