简体   繁体   中英

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 ? 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.

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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