Java System.setOut() – Examples

In this tutorial, we will learn about the Java System.setOut() function, and learn how to use this function to set the standard output stream, with the help of examples.

setOut(PrintStream out)

System.setOut() sets the “standard” output stream with specified PrintStream object.

By default, Console output is the standard output stream. But, using setOut() you can set the standard output stream to a FileOutputStream, etc.

Syntax

The syntax of setOut() function is

</>
Copy
setOut(PrintStream out)

where

ParameterDescription
outThe new standard output stream for the System.

Returns

The function returns void.

Example 1 – setOut()

In this example, we will set a FileOutputStream as the System standard output using setOut(). Any values that are printed to standard output, will be written to the file output.txt specified by FileOutputStream.

If the specified file is not present, new file would be created.

Java Program

</>
Copy
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

public class Example {
	public static void main(String[] args) throws IOException {
		FileOutputStream f = new FileOutputStream("output.txt");
		System.setOut(new PrintStream(f));
		System.out.println("Hello World!");
	}
}

Output

Java System.setOut() example

Conclusion

In this Java Tutorial, we have learnt the syntax of Java System.setOut() function, and also learnt how to use this function with the help of examples.