The Byte Stream Classes
The Byte Stream Classes
The Byte Stream Classes
Byte streams are defined by using two class hierarchies. At the top are two abstract classes:
Input Stream and Output Stream. Each of these abstract classes has several concrete
subclasses that handle the differences between various devices, such as disk files, network
connections, and even memory buffers. To use the stream classes, we must import java.io. The
abstract classes Input Stream and Output Stream define several key methods that the other
stream classes implement. Two of the most important are read ( ) and write ( ), which,
respectively, read and write bytes of data. Both methods are declared as abstract inside Input
Stream and Output Stream. They are overridden by derived stream classes.
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of BufferedReader that is being
created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader,
which converts bytes to characters. To obtain an InputStreamReader object that is linked to
System.in, use the following constructor:
InputStreamReader(InputStream inputStream)
Because System.in refers to an object of type InputStream, it can be used for inputStream.
Putting it all together, the following line of code creates a BufferedReader that is connected
to the keyboard:
After this statement executes, br is a character-based stream that is linked to the console
through System.in.
Reading Characters
To read a character from a BufferedReader, use read( ). The version of read( ) that we will
be using is
Each time that read( ) is called, it reads a character from the input stream and returns it as
an integer value. It returns –1 when the end of the stream is encountered. As we can see,
it can throw an IOException.
The following program demonstrates read( ) by reading characters from the console
until the user types a "q.” Notice that any I/O exceptions that might be generated are
simply thrown out of main( ). Such an approach is common when reading from the console,
but we can handle these types of errors ourselves, if we chose.
// Use a BufferedReader to read characters from the console.
import java.io.*;
class BRRead {
public static void main(String args[])
throws IOException
{
char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
//290 P a r t I : T h e J a v a L a n g u a g e
// read characters
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
This output may look a little different from what you expected, because System.in is line
buffered, by default. This means that no input is actually passed to the program until we
press ENTER. As we can guess, this does not make read( ) particularly valuable for interactive
console input.
PACKAGES :
Collection of classes
C1 CLASS: SUM1()
C2 CLASS : SUM1()
C3 CLASS : SUM2()
NO NAMING CONFLICION