Java Terminal I/O Example

To illustrate the use of InputStreams and OutputStreams, Terminal reads in a stream of bytes from the standard input, typically a computer keyboard, and displays the result to the standard output, typically a computer screen.


Terminal

import java.io.*;

public class Terminal
{

public static void main(String[] args) throws IOException
{
int b;

while ((b = System.in.read() ) != -1)
{
System.out.print((char)b);
}
}
}



In line 1, we use the import statement to abbreviate java.io class names. In line 8, note that java.lang.System.in is the standard input. This is an InputStream object. So we can use one of the overloaded read methods from the InputStream class. This returns a byte, b, of type int. The value –1 is returned by read when the end of the stream is reached. The read method throws an IOException, so we need the throws clause in the declaration of line 5. In line 9, we output to the standard output,
java.lang.System.out. This is not actually an OutputStream object but a PrintStream object (PrintStream being a subclass of OutputStream). So we can use one of the overloaded print methods of the PrintStream class to print out b, having first cast it to a character.

No comments:

Post a Comment