bindings => [name init ...]
Evaluates body in a try expression with names bound to the values
of the inits, and a finally clause that calls (.close name) on each
name in reverse order.
;; Opens the file 'myfile.txt' and prints out the contents. The
;; 'with-open' ensures that the reader is closed at the end of the
;; form.
;;
;; Please note that reading a file a character at a time is not
;; very efficient.
user=> (with-open [r (java.io.FileReader. "myfile.txt")]
(loop [c (.read r)]
(if (not= c -1)
(do
(print (char c))
(recur (.read r))))))
(defn write-csv-file
"Writes a csv file using a key and an s-o-s (sequence of sequences)"
[out-sos out-file]
(spit out-file "" :append false)
(with-open [out-data (io/writer out-file)]
(csv/write-csv out-data out-sos)))
(defmacro with-open
"bindings => [name init ...]
Evaluates body in a try expression with names bound to the values
of the inits, and a finally clause that calls (.close name) on each
name in reverse order."
{:added "1.0"}
[bindings & body]
(assert-args with-open
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
(cond
(= (count bindings) 0) `(do ~@body)
(symbol? (bindings 0)) `(let ~(subvec bindings 0 2)
(try
(with-open ~(subvec bindings 2) ~@body)
(finally
(. ~(bindings 0) close))))
:else (throw (IllegalArgumentException.
"with-open only allows Symbols in bindings"))))
Comments top
No comments for with-open. Log in to add a comment.