Epicurus
Epicurus

Reputation: 2131

Failing to redirect standard output in Java

I am attempting to redirect the console output of a Java library to a JTextArea in my application. The library in question is JPL, a bridge between Java and SWI-Prolog (though I doubt this has much relevance conceptually).

Here is my code:

        PrintStream out = new PrintStream(new MyOutputStream(), true, "UTF-8");
        System.setOut(out);
        System.setErr(out);

        System.out.println("This text is successfully redirected.");

        Hashtable<String, Term> solutions[] = Query.allSolutions("append([1],[2],[1,2])");

When I run this code, the string "This text is successfully redirected" is redirected to my PrintStream as expected. However, the last line of the above snippet generates some text output which is still printed at the Java console instead of in my PrintStream.

What could the method allSolutions(String) be doing so that its output is not redirected? Could it be the fact that it calls an OS process that generates the output (it does call the swipl process)? If so, can I redirect its output without modifying the JPL code?

Upvotes: 2

Views: 363

Answers (1)

Miquel
Miquel

Reputation: 15675

Yes, your assumption is correct: the process being executed is printing directly to the console. What you can do is capture the output of that process and pass it to your PrintStream as shown here by @StijnGeukens: (copy pasted code follows)

String line;
Process p = Runtime.getRuntime().exec(...);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
  System.out.println(line);
}
input.close();

But that's only if you actually have access to the internals of allSolutions.

I do not know a way of capturing any other output, I'm afraid.

Upvotes: 1

Related Questions