|
The following example demonstrates how input is read from the console and printed back. Any I/O errors are caught and sent to the standard error stream. In this example, all the standard streams are used:
System.in is an instance of InputStreamSystem.out is an instance of PrintStream,
which is a subclass of
OutputstreamSystem.err is also an instance of PrintStreamHere is the code.
import java.io.*;
public class Echo {
public static void main (String[] args) {
DataInputStream consoleIn = new DataInputStream(System.in);
String line = "not null";
while( ! line.equals("")) {
try {
line = consoleIn.readLine();
System.out.println(line);
} catch (IOException e) {
System.err.println(e);
break;
}
}
}
}
There are several points to note.
System.in a DataInputStream with
the line
DataInputStream consoleIn = new DataInputStream(System.in);This more refined subclass DataInputStream offers the method
readLine() apart from the basic read().out and err are instances of PrintStream, which is a
subclass of OutputStream. PrintStream offers the
method println, which is more or less the converse of readLine.