简体   繁体   English

Java程序如何完全读取自己的控制台输出?

[英]How can a Java program read its own console output fully?

First of all, I'm aware that if you want to start a process and get the console output from it, you can use for example this code: 首先,我知道如果你想启动一个进程并从中获取控制台输出,你可以使用例如这个代码:

ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
Process proc;
proc = builder.start();
InputStreamReader isr = new InputStreamReader(proc.getInputStream());
BufferedReader reader = new BufferedReader(isr);
String line;
while ((line = reader.readLine()) != null) {
    System.out.println(line);
}

But what if I wanted to get the whole console output from the currently running Java program ? 但是如果我想从当前运行的Java程序中获取整个控制台输出呢? Is it possible to read it without missing anything? 是否可以阅读它而不会遗漏任何东西? I'm sure that the program for showing text in console uses System.out.println() in some places, in most it uses many instances of java.util.logging.Logger , and maybe some other methods somewhere else. 我确信在控制台中显示文本的程序在某些地方使用System.out.println() ,大多数情况下它使用java.util.logging.Logger许多实例,也许还有其他一些其他方法。

By the way, does the Logger class in the end simply use System.out to print text or does it use any other special methods for logging? 顺便说一下, Logger类到底只是使用System.out打印文本还是使用其他任何特殊方法进行日志记录?

Anyway, can I somehow listen to all of these? 无论如何,我能以某种方式倾听所有这些吗?

Thanks in advance 提前致谢

This may not be a complete solution to your problem. 这可能不是您问题的完整解决方案。 But it is one workaround that I have used somewhere. 但这是我在某处使用的一种解决方法。

You can redirect your program standard output to a file and from your program itself you can read that file as it is changed. 您可以将程序标准输出重定向到文件,从程序本身可以读取该文件的更改。

For a console based application, you can redirect your console output in a file using - 对于基于控制台的应用程序,您可以使用以下方法将控制台输出重定向到文件中:

java -cp temp.jar test.Main >> program.log

program.log file will be created with all standard output messages even the program is still running. 即使程序仍在运行,也将使用所有标准输出消息创建program.log文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM