Java Reference
In-Depth Information
most Java I/O operations, you must enclose the read() method in a try-catch
block to catch any possible IOException that might be thrown.
To read a string of characters the above code segment should go inside a loop,
as in
String strInput ="";
while (true) {
try {
int tmp = System.in.read ();
if (tmp == -1) break;
char c = (char) tmp;
strInput = strInput + c;
}
catch (IOException e) {}
}
System.out.println ( " Echo =" + strInput);
The return of a -1 value indicates the end of the input. Since the byte that is read
goes into the low 8 bits of a 32-bit int value, a genuine data value can never set
the sign bit.
We see that System.in is obviously an inelegant and inefficient way to carry
out routine text input. We therefore normally wrap this input stream with classes
that provide more powerful methods.
As discussed earlier, the “buffer” wrapper classes provide for efficient trans-
mission of stream bytes. In addition, they typically add various useful methods.
In the BufferedReaderApp example below, we wrap System.in with the
InputStreamReader and then wrap this instance with BufferedReader .
We take advantage of the readLine() method in BufferedReader and obtain
awhole line of input all at once rather than looping over reads of one character at a
time. This technique also removes the need for type conversion from int to char .
import java.io.*;
/** Demonstrate the BufferedReader class for wrapping a
* reader object and providing the readLine () method. **/
public class BufferedReaderApp
{
public static void main (String arg[]) {
// System.in std input stream already opened by default.
// Wrap in a new reader stream to obtain 16 bit
// capability.
InputStreamReader reader =
new InputStreamReader (System.in);
 
Search WWH ::




Custom Search