Home » Java programming language

Java System class setOut() method with example

System class setOut() method: Here, we are going to learn about the setOut() method of System class with its syntax and example.
Submitted by Preeti Jain, on September 12, 2019

System class setOut() method

  • setOut() method is available in java.lang package.
  • setOut() method is used to assign again the standard output stream or in other words, this method is used to reassign the standard output stream.
  • The setOut() method is redirected because it does not write the output on the editor.
  • The setOut() method does not write the output to the proper JTextArea like setErr() method and it returns null.
  • This is a static method, so this method is accessible with the class name too.
  • setOut() method may throw an exception while writing the output to the standard output stream and the description is given below
    SecurityException: In this exception, the checkPermission() method does not allow reassigning of the latest standard output stream when the security manager exists.

Syntax:

    public static void setOut(PrintStream set_out);

Parameter(s):

  • set_out – represents the latest standard output stream.

Return value:

The return type of this method is void, it returns nothing

Example:

// Java program to demonstrate the example of 
// setOut() method of System Class.

import java.lang.*;
import java.io.*;

public class SetOutMethod {
    public static void main(String[] args) throws Exception {
        // Creating an instance of File
        File file = new File("E://Programs//getProperties().doc");

        // By using exists() method returns true if file exists
        System.out.println("file existing is  = " + file.exists());

        // Creating an instance of FileOutputStream fos
        FileOutputStream fos = new FileOutputStream(file);
        System.setOut(new PrintStream(fos));
        System.out.println("File Writing Done!!");

    }
}

Output

E:\Programs>javac SetOutMethod.java
E:\Programs>java SetOutMethod
file existing is  = true

Output – if file does not exist

E:\Programs>javac SetOutMethod.java
E:\Programs>java SetOutMethod

Exception in thread "main" java.io.FileNotFoundException: 
    E:/Programs/getProperties().doc (No such file or directory)
	at java.base/java.io.FileOutputStream.open0(Native Method)
	at java.base/java.io.FileOutputStream.open(FileOutputStream.java:299)
	at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:238)
	at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:188)
	at SetOutMethod.main(SetOutMethod.java:16)


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.