Hide Java output

I am using an external library. When you call the method of this library, it prints the text to the console. I want to hide this text from the console. How is this possible?

Thanks at Advance

+3
source share
3 answers

You can override system.out (I believe this is System.setOut ()) I believe that you can set it to NULL (fixed - you cannot set it to NULL), but you can set it to ANY output stream.

I did something interesting with this once. I saved "System.out" and then redirected it to my own output stream with the code in the "print" method - this method is called whenever someone prints on the stream.

, , , , System.out.println(). - โ€‹โ€‹ .

, , , .

, . , , , "BK:", .

.

( , , )

// class variable
public static final OutputStream out;

{
    out=System.getOutputStream();// I may have the actual name wrong, but it close
    System.setOutputStream(new OutputStreamThatDoesNothing());
}

:

Redirect.out("Hello");

, System.out.

, - , :

OutputStream tmp=System.getOutputStream();
System.setOutpuatStream(nullStream);
callOffensiveLibraryMethod();
System.setOutputStream(tmp);

, , .

+5
private PrintStream realSystemOut = System.out;
private static class NullOutputStream extends OutputStream {
    @Override
    public void write(int b){
         return;
    }
    @Override
    public void write(byte[] b){
         return;
    }
    @Override
    public void write(byte[] b, int off, int len){
         return;
    }
    public NullOutputStream(){
    }
}
void someMethod(){
    System.setOut(new PrintStream(new NullOutputStream());
    realSystemOut.println("Hello World!"); //prints Hello World!
    System.out.println("Hello World!"); //nothing!
    System.setOut(realSystemOut);
    System.out.println("Hello World!"); //prints Hello World!
}
+3

Set System.out to NullOutputStream. Apacahe.commons has one available.

If you want to print it, you can write a funny hack.

private static final PrintStream SYSTEM_OUT = System.out();

public static void debug(String debug){
     SYSTEM_OUT.println(debug);
}

Someone else in code

  System.setOut(new PrintStream(new NullOutputStream()));  
+2
source

Source: https://habr.com/ru/post/1768710/


All Articles