Redirect to a NULL deviceTag(s): IO


This can be useful if you want to suppress all output.
// Unix style
PrintStream nps = new PrintStream(new FileOutputStream("/dev/null"));
System.setErr(nps);
System.setOut(nps);

//Windows style
PrintStream nps = new PrintStream(new FileOutputStream("NUL:"));
System.setErr(nps);
System.setOut(nps);


//One-liner style : subclass OutputStream to override the write method ...
System.setOut(new java.io.PrintStream(
    new java.io.OutputStream() {
       public void write(int b){}
    }
 ));
You may want to suppress output done with the regular System.out but maintain the ability to write to the original streams directly when necessary.
// Keep a copy of the original out stream.
PrintStream original = new PrintStream(System.out);

  // replace the System.out, here I redirect to NUL (for demonstration)
  System.setOut(new PrintStream(new FileOutputStream("NUL:")));
  System.out.println("bar");  // no output

// The original stream is still available
original.println("foo");  // output to stdout
See also Get faster console output (System.out.println() replacement).
blog comments powered by Disqus