I want to create a Clojure macro that can read a file, when the file is read successfully the stream should be closed.
(import '(java.io FileReader File))
(defmacro read([x y]
`(let ~x
(try ~y
(. x close)
(catch Exception e# e#)))))
Called like this,
(read [stream (java.io.FileReader (java.io.File "somefile.txt"))] (. stream read)))
Results in this error
java.lang.Exception: No such var: user/x (NO_SOURCE_FILE:8)
Does anyone have any suggestions, thanks.
Aren’t you looking for
with-open, unless there is some reason that you want to explicitly use a macro?According to the ClojureDocs page, it ensures that the reader is closed at the end of the form.
Hopefully that helps!