What is the System setOut() function in Java?

The static System.setOut() method is used to reassign the standard output stream.

This method first uses the checkPermission() method to check for the security manager and its permissions.

Syntax


static void setOut(PrintStream out)

Parameters

The setOut() method takes an argument of class PrintSteam type:

  • out: Standard output stream.

Return value

The setOut() method does not return a value.

setOut() returns SecurityException if the checkPermission() method does not allow reassigning or the security manager exits.

Example

In the code snippet below, we use the System.setOut() method to change the default console output stream object to file data.txt output stream.

The system.out.println() method outputs data into the file instead of the console.

EdPresso.java
data.txt
// Loading libraries
import java.lang.*;
import java.io.*;
// Main class
public class EdPresso {
public static void main(String[] args) throws Exception {
// creating file for output stream
FileOutputStream stream = new FileOutputStream("data.txt");
System.out.println("Check data.txt for output in current directory");
// set new stream object
System.setOut(new PrintStream(stream));
System.out.println("Learn in-demand tech skills in half the time");
}
}

Free Resources