Last active
March 13, 2019 16:50
-
-
Save jeremyheiler/66ba8ff62650fb0de700 to your computer and use it in GitHub Desktop.
Hijacking System.out with Clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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