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 librariesimport java.lang.*;import java.io.*;// Main classpublic class EdPresso {// main methodpublic static void main(String[] args) throws Exception {// existing fileSystem.out.println("---Demo Code for System.setIn() Method---");InputStream stream = new FileInputStream("data.txt");System.setIn(stream);// read the first character in the filechar ch = (char) System.in.read();System.out.println("Output: " + ch);}}