如何从 System.out 中抓取数据作为字符串?

How to grab the data from System.out as string?

对于我在 java 中编写的一种类似于 IDE 的系统,我想复制并显示一个与标准控制台工作方式相同的控制台。因此,我需要一种方法来读取写入 stdoutstderr 的所有内容。 是否有类似于 Process.getInputStream() 函数的东西适用于当前 Java 进程,而不仅仅是外部进程? 希望避免更改所有标准输出命令。

非常感谢!

使用 System.setOut() 和 System.setErr() 用您的自定义流覆盖默认输出和错误流。

像这样

  FileOutputStream f = new FileOutputStream("file.txt");

  System.setOut(new PrintStream(f));

  // this text will get redirected to youe file
  System.out.println("This is System class!!!");