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.
static void setIn(InputStream in)
This method takes a class inputStream
instance as a parameter:
in
: A standard input stream.It does not return any value.
It will return SecurityException
if the checkPermission()
method does not allow to reassign or security manager exits.
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.
// 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);}}