I know that the System.in of the System class is an instance of a specific subclass of InputStream, because the read () method of InputStream is abstract, and System.in must override this method. According to the document on the read () method of InputStream:
public abstract int read () throws IOException
Reads the next byte of data from the input stream. The byte of the value is returned as an int in the range from 0 to 255. If the byte is unavailable because the end of the stream has been reached, the value -1 is returned. This method blocks until input is available, the end of the stream is detected, or an exception is thrown.
The subclass should provide an implementation of this method.
Returns:
next byte of data or -1 if the end of the stream is reached.
It produces:
IOException - if an I / O error occurs.
The read () method should return -1 if the end of the stream is reached. My question is when will System.in.read () return -1?
The following is sample code:
import java.io.*; class SystemInTest{ public static void main(String[] args) throws IOException{ InputStream in = System.in;
Run this code and type "abc" and then "Enter", the result (under Linux):
97 98 99 10
Then the application is locked and waiting for another input. But I thought that the statement in the while loop "ch = in.read ()" should continue to work and return -1 after reading the line termination character and printing 10 on the console. If so, the application should be terminated. But he is blocked.
As a comparison, if I uncomment the commented line using the file with the content "abc \ n" as the byte input stream, the application stops waiting because -1 is returned.
Is it true that System.in.read () never returns -1? If so, why is the implementation of the read () method in System.in different from other InputStream subclasses such as FileInputStream?