ClojureDocs

Nav

Namespaces

with-open

clojure.core

Available since 1.0 (source)
  • (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.
4 Examples
;; 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 (clojure.java.io/input-stream "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)))

;; Try to read 3 lines of text from a test file and return them (to the REPL)
;; as a list:
(with-open [r (clojure.java.io/reader "test-0.txt")]
  (binding [*in* r] (repeatedly 3 read-line)))

;; The above returns a lazy seq without reading any lines while *in* is bound
;; to the file, resulting in the original *in* (usually stdin) being read.
;; To fix, wrap the body within the *in* binding in (doall ...):
(with-open [r (clojure.java.io/reader "test-0.txt")]
  (binding [*in* r] (doall (repeatedly 3 read-line))))

;; That ensures the sequence will be fully realized with the binding of *in*
;; still in effect, thus reading all 3 lines from the test file.
;Process multiple files with a transducer as if it's one file
;Not lazy, but processes a line at a time

(defn process-file
  [t file]
  (with-open [rdr (io/reader file)]
    (into []
          t
          (line-seq rdr))))

(defn process-files
  [t files]
  (into []
        (comp (mapcat (fn [file] (process-file t file))))
        files))

(apply + (process-files (comp (map count))
                        ["test-0.txt" "test-1.txt" "test-2.txt"]))
See Also

Opens a reader on f and reads all its contents, returning a string. See clojure.java.io/reader for...

Added by fhur

Attempts to coerce its argument into an open java.io.InputStream. Default implementations always ...

Added by phreed
0 Notes
No notes for with-open