J2EEOnline J2EE 






Java Streams  «Prev  Next»
Lesson 2Reading data from a stream
ObjectiveWrite program that reads data from System.in.

Reading Data from Java Streams

Write a program that reads data from System.in using an InputStream and prints the numeric value of each byte read.
The fundamental method of the InputStream class is read().

Read 10 bytes from System.in

The following code fragment reads 10 bytes from the System.in input stream and stores them in the int array b:
int[] b = new int[10];
for (int i = 0; i < b.length; i++) {
  b[i] = System.in.read();
}


Notice that although read() is reading a byte, it returns an int. If you want to store the raw bytes instead, you can cast the int to a byte

If read() encounters the end-of-stream, it returns -1 instead.
You use this as a end of stream flag to watch for the end-of-stream.

reading data stream exception The read() method is declared to throw an IOException. The java.io.IOException is a checked exception, so you'll need to wrap all calls to this method in a try-catch block or declare that your own method throws IOException.
The read() method waits or blocks until a byte of data is available and ready to be read. Input and output can be slow, so if your program is doing anything else of importance, you should try to put I/O in its own thread.
Although read() is declared abstract, all the concrete subclasses of InputStream you'll actually be dealing with do implement it. Because InputStream is abstract, you can never instantiate it directly, only its subclasses.

Reading Data - Exercise

Click the Exercise link below to write a program that reads data from System.in using an InputStream and prints the numeric value of each byte read using the System.out.println() method.
Reading Data - Exercise