a shot of dev knowledge

RELATED TAGS

What is the System setIn() function in Java?

This static method System.setIn() from the class java.lang.System is used to reassign the standard input stream.

First, this method checks for the security manager and its permissions by using the checkPermission() method.

Syntax


static void setIn(InputStream in)

Parameters

This method takes a class inputStream instance as a parameter:

  • in: A standard input stream.

Return value

It does not return any value.

It will return SecurityException if the checkPermission() method does not allow to reassign or security manager exits.

Example

In the code snippet below, we are simply opening a file named data.txt by using the FileInputStream() function and passing it to System.setIn() to set input stream.

EdPresso.java
data.txt
// Load libraries
import java.lang.*;
import java.io.*;
// Main class
public class EdPresso {
      // main method
   public static void main(String[] args) throws Exception {
      // existing file
      System.out.println("---Demo Code for System.setIn() Method---");
      InputStream stream = new FileInputStream("data.txt");
      System.setIn(stream);
      // read the first character in the file
      char ch = (char) System.in.read();
      System.out.println("Output: " + ch);              
   }
}

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring