Skip to content

Instantly share code, notes, and snippets.

@malcolmgreaves
Last active September 29, 2016 22:30
Show Gist options
  • Save malcolmgreaves/1b6cba6bd1e7a7818655bf27f3168858 to your computer and use it in GitHub Desktop.
Save malcolmgreaves/1b6cba6bd1e7a7818655bf27f3168858 to your computer and use it in GitHub Desktop.
Turn on or off the standard out & error streams of a JVM program, written in Scala.
object OnOffStdOutErrG {
import java.io.{OutputStream, PrintStream}
private[this] val (originalStdOut, originalStdErr) = (System.out, System.err)
/** A PrintStream for "/dev/null": all write() invocations are no-ops. */
val devnull = new PrintStream(
new OutputStream() {
override def write(ignore: Int): Unit = { /* nothing !! */ }
}
)
/** Sets std{out,err} to "/dev/null", returns the original std{out,err} streams. */
@synchronized def off(): Unit = {
System.setOut(devnull)
System.setErr(devnull)
}
/** Sets std{out,err} to the original streams. */
@synchronized def on(): Unit = {
System.setOut(originalStdOut)
System.setErr(originalStdErr)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment