Skip to content

Instantly share code, notes, and snippets.

@jeremyheiler
Last active March 13, 2019 16:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremyheiler/66ba8ff62650fb0de700 to your computer and use it in GitHub Desktop.
Save jeremyheiler/66ba8ff62650fb0de700 to your computer and use it in GitHub Desktop.
Hijacking System.out with Clojure
(defmacro with-system-out-str
[& body]
`(let [out# System/out
buf# (java.io.ByteArrayOutputStream.)
prs# (java.io.PrintStream. buf#)
wtr# (java.io.OutputStreamWriter. prs#)]
(try
(System/setOut prs#)
(binding [*out* wtr#]
(do ~@body))
(finally
(.flush wtr#)
(.flush prs#)
(System/setOut out#)))
(.toString buf#)))
(with-system-out-str (.print System/out "hi") (println" there"))
;; "hi there\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment