System.out.println, by default, logs a message to console if the process has a reference to console window. For subprocesses, by default, there is no console attached. By making use of System.setOut we can redirect the output to a file or some other stream.
Code to redirect the output stream to a file.
File out = new File("/tmp/out.txt");
PrintStream outputStream = new PrintStream(out);
System.setOut(outputStream);
Now,
System.out.println("Hello world!");
This will result in Hello world! getting printed in /tmp/out.txt file.
Similarly, System.setIn and System.setErr APIs are also available and can be used wherever needed.
Code to redirect the output stream to a file.
File out = new File("/tmp/out.txt");
PrintStream outputStream = new PrintStream(out);
System.setOut(outputStream);
Now,
System.out.println("Hello world!");
This will result in Hello world! getting printed in /tmp/out.txt file.
Similarly, System.setIn and System.setErr APIs are also available and can be used wherever needed.