【问题标题】:Intercept system.out in java [duplicate]在java中拦截system.out [重复]
【发布时间】:2020-11-06 13:29:46
【问题描述】:

我有一个具有 system.out 的方法,它在 main 中使用。如何拦截该打印并将其分配给 String 变量?我也不希望它被打印出来。

public void print()
System.out.println("hello");

---main---
print(); // need to intercept this 
String str = print(); // need assign the contents of the print() to str and not show the contents of print in the console

编辑:由于某些限制,我无法创建 .txt,也无法更改方法的代码。我需要在 main 中进行所有更改

【问题讨论】:

  • 将其设置为指向StringWriterPrintWriter
  • @dan1st 对不起,你能详细说明一下代码吗?
  • 如果可能,请更改代码以免使用任何全局状态。 (否则,System.setOut。)
  • @TomHawtin-tackline 哪个代码?我不确定你所说的全局状态是什么意思
  • @Ernest 使用System.out的代码。将其替换为将打印到传入的PrintStream 对象(或类似类型的对象)的代码。 /全局状态通常以static变量的形式隐藏在某处。它只是意味着不是本地的变量状态。

标签: java system


【解决方案1】:

您可以致电System.setOut() 更改System.out 使用的PrintStream。您可能还想将setErr() 呼叫到同一个PrintStream

为了说明,让我们使用一个标准的“Hello World”程序。

public static void main(String[] args) {
    System.out.println("Hello World");
}

输出

Hello World

我们现在将输出打印流替换为在缓冲区中捕获所有输出的打印流。我们确实保留了原始打印流的副本,以便我们可以在最后打印一些真实的东西。

public static void main(String[] args) {
    PrintStream oldSysOut = System.out;
    ByteArrayOutputStream outBuf = new ByteArrayOutputStream();
    try (PrintStream sysOut = new PrintStream(outBuf, false, StandardCharsets.UTF_8)) {
        System.setOut(sysOut);
        System.setErr(sysOut);
        
        // Normal main logic goes here
        System.out.println("Hello World");
    }
    String output = new String(outBuf.toByteArray(), StandardCharsets.UTF_8);
    oldSysOut.print("Captured output: \"" + output + "\"");
}

输出

Captured output: "Hello World
"

从这里可以看出,所有输出都被捕获,包括来自println() 调用的换行符。

【讨论】:

  • 知道为什么正常的 System.outprintln() 之后不起作用吗?
猜你喜欢
  • 1970-01-01
  • 2015-11-22
  • 1970-01-01
  • 2015-08-22
  • 2020-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-08
相关资源
最近更新 更多