Java Reference
In-Depth Information
those bytes and convert them into characters in your current character set. Sys-
tem.in is passed to the InputStreamReader() constructor to create an In-
putStreamReader object.
InputStreamReader knows about characters, but not about lines. It is the
BufferedReader class's job to detect line breaks in the input stream, and to enable
you to conveniently read a line at a time. BufferedReader also aids efficiency by
allowing physical reads from the input device to be done in different-size chunks than
by which your application consumes the data. This aspect can make a difference when
the input stream is a large file rather than the keyboard.
Following is how the program in Listing 1-7 makes use of an instance (named
readIn ) of the BufferedReader class to read a line of input from the keyboard:
numberAsString = readIn.readLine();
Executing this statement triggers the following sequence:
1. System.in returns a sequence of bytes.
2. InputStreamReader converts those bytes into characters.
3. BufferedReader breaks the character stream into lines of input.
4. readLine() returns one line of input to the application.
I/O calls must be wrapped in try...catch blocks. These blocks catch any ex-
ceptions that may occur. The try part in the example will fail in the event a conver-
sion is unsuccessful. A failure prevents the numberIsValid flag from being set to
true , which causes the do loop to make another iteration so that the user can try
again at entering a valid value.
The following statement at the top of Listing 1-7 deserves some mention:
import java.io.*;
This statement makes available the classes and methods defined in the java.io
package. These include InputStreamReader and BufferedReader . Also in-
cluded is the IOException class used in the first try...catch block.
1-8. Documenting Your Code
Search WWH ::




Custom Search