teaLeef
teaLeef

Reputation: 1989

Output redirection in Java

How can I redirect an output in java?

I am running a program in eclipse. My code is as follows:

  public static void main(String[] args) throws Exception{
    /* Redirect output to file */
    File file = new File("fileName");
    FileOutputStream fos = new FileOutputStream(file);
    PrintStream ps = new PrintStream(fos);
    System.setOut(ps);

    OtherClass.main(args);
  }

Without the output redirection I wrote above, the code returns some values in black and some in red (which are not errors, but parameters called in OtherClass).

The redirection above writes the text that appeared in black in the eclipse console in my file, but the output in read is written on console and not in my file.

How can I do the contrary and print the red text in my file and not the black one? And why does eclipse use different colors for this output?

Upvotes: 1

Views: 202

Answers (3)

Pshemo
Pshemo

Reputation: 124285

How can I do the contrary and print the red text in my file and not the black one?

Instead of redirecting output from standard output (System.out) to file, redirect output from error stream (System.err). In other words instead of

System.setOut(ps);

use

System.setErr(ps);
//        ^^^

And why does eclipse use different colors for this output?

So you could see which output comes from System.out (black), and which from System.err (red - which handles printing Exceptions).

Upvotes: 1

misberner
misberner

Reputation: 3688

Red output in the Eclipse console is text being printed onto the standard error stream (System.err). In order to accomplish that only the text being printed in red is written to the file you need to replace your call to System.setOut(ps); with System.setErr(ps);.

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201537

Calling System.setOut() redirects stdout, you need to call System.setErr() to redirect stderr - something like,

// System.setOut(ps);
System.setErr(ps); // <-- for std err

Upvotes: 1

Related Questions