我正在使用一个外部库。当我调用这个库的某个方法时,它会在控制台上输出一些文本。我想隐藏控制台上的这些文本。有什么办法吗?
提前感谢。
提前感谢。
// class variable
public static final OutputStream out;
{
out=System.getOutputStream();// I may have the actual name wrong, but it's close
System.setOutputStream(new OutputStreamThatDoesNothing());
}
此时任何对以下内容的调用:
Redirect.out("Hello");
应该与对System.out的调用相同。
因为没有奇技淫巧,如果你真的想要,也可以这样做:
OutputStream tmp=System.getOutputStream();
System.setOutpuatStream(nullStream);
callOffensiveLibraryMethod();
System.setOutputStream(tmp);
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!
}
对于那些寻找2020年版本并且不需要外部库的空流的人:
PrintStream out = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
//
//do stuff with library...
//
System.setOut(out);
自Java 11版本起可用。
将System.out设置为NullOutputStream。apacahe.commons中有一个可用的。
如果您想相应地打印出来,可以编写一个有趣的hack。
private static final PrintStream SYSTEM_OUT = System.out();
public static void debug(String debug){
SYSTEM_OUT.println(debug);
}
代码的其他部分
System.setOut(new PrintStream(new NullOutputStream()));