Java - Swallow All Data Sent to the Standard Output

Introduction

If you do not want to go for a new class, use an anonymous class.

System.setOut(new PrintStream(new OutputStream() {
                                public void write(int b) {
                                        // Do nothing
                                }}));

Or you can create your own concrete component class in the OutputStream class family.

Then, create a PrintStream object by wrapping an object of the new class and set it as the standard output using the System.setOut() method.

Demo

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

public class Main {
  public static void main(String[] args) {
    PrintStream ps = new PrintStream(new DummyStandardOutput());

    // Set the dummy standard output
    System.setOut(ps);/* w  w  w  . j av  a 2  s.c  o m*/

    // The following messages are not going anywhere
    System.out.println("Hello world!");
    System.out.println("Is someone listening?");
    System.out.println("No. We are all taking a nap!!!");
  }
}

class DummyStandardOutput extends OutputStream {
  public void write(int b) throws IOException {
    // Do not do anything. Swallow whatever is written
  }
}

Related Topic