ClojureDocs

Nav

Namespaces

writer

clojure.java.io

Available since 1.2
  • (writer x & opts)
Attempts to coerce its argument into an open java.io.Writer.
 Default implementations always return a java.io.BufferedWriter.
  Default implementations are provided for Writer, BufferedWriter,
 OutputStream, File, URI, URL, Socket, and String.
  If the argument is a String, it tries to resolve it first as a URI, then
 as a local file name.  URIs with a 'file' protocol are converted to
 local file names.
  Should be used inside with-open to ensure the Writer is properly
 closed.
3 Examples
;; This example shows the use of the ':append' option
(defn write-file []
  (with-open [w (clojure.java.io/writer  "f:/w.txt" :append true)]
    (.write w (str "hello" "world"))))
;; This example shows the use of the ':encoding' option.
(require '(clojure.data.xml :as xml))

(let [tags (xml/element :foo {:foo-attr "foo value"}
                    (xml/element :bar {:bar-attr "bar value"}
                             (xml/element :baz {} "The baz value")))]
  (with-open [out-file (clojure.java.io/writer "/temp/bar.xml" :encoding "UTF-8")]
    (xml/emit tags out-file))
  (with-open [input (clojure.java.io/reader "/temp/bar.xml")]
    (xml/parse input)))
;;=> #clojure.data.xml.Element{:tag :foo, :attrs {:foo-attr "foo value"}, 
;;    :content 
;;       (#clojure.data.xml.Element{:tag :bar, :attrs {:bar-attr "bar value"},
;;         :content 
;;             (#clojure.data.xml.Element{:tag :baz, :attrs {}, :content ("The baz value")})})}
;; When a Writer is created from a Socket using `with-open`, the 
;; underlying Socket is closed along with the Writer.

;; Create the Socket.
(require '[clojure.java.io :as io])
(def socket (java.net.Socket.))
(.connect socket (java.net.InetSocketAddress. "www.google.com" 80))
(.isClosed socket)
;;=> false

;; Write to the Socket.
(with-open [w (io/writer socket)]
  (.write w "GET / HTTP/1.0\n\n")
  (.flush w))
(.isClosed socket)
;;=> true

;; Attempt to read from the Socket.
(with-open [r (io/reader socket)
            s (java.io.StringWriter.)]
  (io/copy r s))
;;=> java.net.SocketException: Socket is closed
See Also

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

Added by cgray

Factory functions that create ready-to-use, buffered versions of the various Java I/O stream type...

Added by jafingerhut

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

Added by jafingerhut

Opposite of slurp. Opens f with writer, writes content, then closes f. Options passed to clojure....

Added by jafingerhut
0 Notes
No notes for writer