You're viewing version 1.2.0 of with-open. The latest stable version of Clojure Core is 1.3.0.
1.2.0 Arrow_down_16x16

with-open

clojure.core

  • (with-open bindings & body)
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.

2 Examples top

  • ;; 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)))
    
    
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:2911 top

(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"))))
Vars in clojure.core/with-open: = cond count defmacro even? subvec symbol? vector? concat let list seq

Comments top

No comments for with-open. Log in to add a comment.