iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🙆‍♀️

How to temporarily disable standard output in Java

に公開

This is a method for temporarily turning off standard output in Java.

Repl.it - StdOutToNull

Code

import java.io.*;
import java.util.*;

class Main {
  public static void main(String[] args) {
    PrintStream stdout = System.out;

    System.setOut(new PrintStream(new OutputStream() {
      public void write(int b) { /* noop */ }
    }));
    System.out.println("no print");
    System.out.println("no print");

    System.setOut(stdout);
    System.out.println("print");
    System.out.println("print");
  }
}
print
print

We are using System.setOut to switch between the "default output" and an "OutputStream that does nothing."

snippet

Code for just the snippet part.

PrintStream stdout = System.out;
System.setOut(new PrintStream(new OutputStream() {
  public void write(int b) { /* noop */ }
}));
// out off

System.setOut(stdout);
// out on
GitHubで編集を提案

Discussion