Input Stream Classes:
Input stream classes are byte stream classes that are used to read 8 bit byte data. All the input stream classes are arranged in a hierarchy structure. InputStream class is the root class in the hierarchy. This class is an abstract class, which can’t be used for object creation. It provides the basic functionalities for performing the following operations on input:
- Reading bytes
- Closing streams
- Marking positions in streams
- Skipping ahead in streams and
- Finding the number of bytes in a stream data
The following figure shows the class hierarchy of input stream classes:
Fig. : InputStream class hierarchy (partial)
InputStream class defines the following methods for reading bytes
int read() throws IOException
int read(byte b[]) throws IOException
int read(byte b[], int offset, int length) throws IOException
Subclasses of InputStream implement the above mentioned methods. Other methods defined in InputStream are:
available()
skip()
reset()
close()
The class DataInputStream is a sub class that extends FilterInputStream and implements the interface DataInput. Therefore, the DataInputStream class implements the methods described in DataInput in addition to the methods inherite3d from InputStream class. The DataInput interface contains the following method:
- readShort()
- readLine()
- reading()
- readChar()
- readLong()
- readBoolean()
- readFloat()
- readDouble()
The example below illustrates code to read a character.
//First create an object of type FileInputStream type using the name of the file.
FileInputStream inp = new FileInputStream("filename.ext");
//Create an object of type DataInputStream using inp.
DataInputStream dataInp = new DataInputStream(inp);
int i = dataInp.readInt();
Output Stream Classe:
The OutputStream class is the base class of all output streams in the Java IO API. Subclasses include the BufferedOutputStream and the FileOutputStream among others. OutputStream's are used for writing byte based data, one byte at a time. Here is an example: The write() method of an OutputStream takes an int which contains the byte value of the byte to write.
Subclasses of OutputStream may have alternative write() methods. For instance, the DataOutputStream allows you to write Java primitives like int, long, float, double, boolean etc. with its corresponding methods writeBoolean(), writeDouble() etc. The following figure shows the class hierarchy of OutputStream classes:
Fig. : OutputStream class hierarchy (partial)
OutputStream class defines the following methods for writing bytes –
void write(int b) throws IOException
void write(byte b[]) throws IOException
void write(byte b[], int offset, int length) throws IOException
Subclasses of OutputStream implement the above mentioned methods.