I am currently trying get whatever is printed into the console and store it as a string. I must be able to hook into the System.out.println method as errors and anything created by anyone other than me must end up in the console. I have already tried using a scanner but that is only for typing into the console and I read the documentation on pipes but from my understanding you still need to give the pipe data rather than the pipe getting it from the console. Does anyone know what I need to use to get the strings printed from the console?
Asked
Active
Viewed 308 times
1
-
What code do you need? what I need is to hook into the system.out.println method – Hamish May 02 '16 at 06:32
-
2This is unclear. Are you saying you want to intercept the output of all other programs that write to a "console"? What if there are 10 console windows open? Do you want to capture all of them? Why do you think the OS would allow you to read output from other programs if it was not explicitly piped to your program? – Jim Garrison May 02 '16 at 06:33
-
Yes i want to intercept what is being printed to my console including errors and things from library I'm using i do not need to access the console of any other programs – Hamish May 02 '16 at 06:35
-
Well, System has a setOut() method. But I've never seen any decent library write to System.out directly. They all use a logging framework. Maybe you should just configure logging correctly. What is your use case? Why are you trying to do that? – JB Nizet May 02 '16 at 06:43
-
Look at this answer: http://stackoverflow.com/a/30665299/1126273 I think he didn't add any examples, but you just have to `ConsoleOutputCapturer c = new ConsoleOutputCapturer(); c.start();` and stop when you don't want to capture anymore. – Balázs Édes May 02 '16 at 06:45
2 Answers
0
You could redirect the console prints to your own stream, see this answer!

Community
- 1
- 1

Joakim Ericsson
- 4,616
- 3
- 21
- 29
0
I used Joacim Ericsson's resource to solve my problem. First of all i created a Output stream for my text area which was where my data was going.
public class ConsoleRedirection extends OutputStream{
private JTextArea textArea;
public ConsoleRedirection(JTextArea textArea) {
this.textArea = textArea;
}
@Override
public void write(int b) throws IOException {
textArea.append(String.valueOf((char)b));
}
}
Then i just created a print stream using my output stream and set System.out to my custom print stream.
PrintStream printStream = new PrintStream(new ConsoleRedirection(console));
System.setOut(printStream);
System.setErr(printStream);

Hamish
- 77
- 1
- 10