java - Capturing System/out in Clojure -
i'm working java package outputs text console , need capture text in string, i'm not sure how this. looking @ clojure documentation seemed have wrap java call in with-out-str
isn't working me.
minimal code example: if try
(with-out-str (.println (system/out) "foo"))
i'm hoping string value "foo", it's still outputting console instead. doing wrong?
java's system.out.println(...)
call println
method of printstream
instance. need replace system.out
stream own instance , capture content:
(import [java.io bytearrayoutputstream printstream]) (def out-buffer (java.io.bytearrayoutputstream.)) (system/setout (java.io.printstream. out-buffer true "utf-8")) (defn out-str [] (.tostring out-buffer "utf-8"))
watch out in repl though because uses system.out
print results when replace globally, break repl instance.
you can write macro capture content of system.out
, restore original printstream
instance:
(defmacro with-system-out-str [& body] `(let [out-buffer# (bytearrayoutputstream.) original-out# system/out tmp-out# (printstream. out-buffer# true "utf-8")] (try (system/setout tmp-out#) ~@body (finally (system/setout original-out#))) (.tostring out-buffer# "utf-8"))) (with-system-out-str (.println system/out "hi")) ;; => "hi\n"
Comments
Post a Comment