Resetting Standard output Stream

JavaIo

Java Problem Overview


I know that there is a function in Java to set Standard Output Stream to any user defined value using System.setOut method..

But is there any method to reset the standard output to the one which was stored earlier or the one which is standard output?

Java Solutions


Solution 1 - Java

You can get hold of the file descriptor for standard out through FileDescriptor.out. To reset standard out to print to console, you do

System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));

Another way is to simply hold on to the original object, as follows:

PrintStream stdout = System.out;
System.setOut(new PrintStream(logFile));

// ...

System.setOut(stdout);                   // reset to standard output

Solution 2 - Java

This is an old question, but it turns up in Google search all the time and I wanted to correct it. You can actually get it, by using the FileDescriptor class. Calling new PrintStream(new FileOutputStream(FileDescriptor.out))) should give you something which prints to stdout.

import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.PrintStream;


public static void main(String [] args) {
	System.err.println("error.");
	System.out.println("out.");
	System.setOut(System.err);
	System.out.println("error?");
	System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
	System.out.println("out?");
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMahesh GuptaView Question on Stackoverflow
Solution 1 - JavaaioobeView Answer on Stackoverflow
Solution 2 - JavaCharles CooperView Answer on Stackoverflow