Object Oriented Programming: Unit IV: I/O, Generics, String Handling

Java I/O Stream

Definition, types with Example Java Programs

Stream is basically a channel on which the data flow from sender to receiver. An input object that reads the stream of data from a file is called input stream.

UNIT IV : I/O, Generics, String Handling

I/O Basics

Stream

Definition :

• Stream is basically a channel on which the data flow from sender to receiver.

• An input object that reads the stream of data from a file is called input stream.

• The output object that writes the stream of data to a file is called output stream.

Byte Stream and Character Stream

• In Java input and output operations are performed using streams. And Java implements streams within the classes that are defined in java.i

• There are basically two types of streams used in Java.

1. Byte stream

2. Character stream

Byte Stream

• The byte stream is used for inputting or outputting the bytes.

• There are two super classes in byte stream and those are InputStream and OutputStream from which most of the other classes are derived.

• These classes define several important methods such as read() and write().

• The input and output stream classes are as shown in Fig. 4.1.1 and Fig. 4.1.2.


Character Stream

• The character stream is used for inputting or outputting the characters.

•  There are two super classes in character stream and those are Reader and Writer.

• These classes handle the Unicode character streams.

• The two important methods defined by the character stream classes are read() and Write() for reading and writing the characters of data.

• Various Reader and Writer classes are -

Reader and InputStream define similar APIs but for different data types. For example, Reader contains these methods for reading characters and arrays of characters:

int read()

int read(char buf[])

int read(char buf[], int offset, int length)

InputStream defines the same methods but for reading bytes and arrays of bytes:

int read()

int read(byte buf[])

int read(byte buf[], int offset, int length)

Writer and OutputStream are similarly parallel. Writer defines these methods for writing characters and arrays of characters:

int write(int c)

int write(char buf[])

int write(char buf[], int offset, int length)

And OutputStream defines the same methods but for bytes:

int write(int c)

int write(byte buf[])

int write(byte buf[], int offset, int length)

Comparison between Byte Stream and Character Stream

Review Questions

1.What is meant by stream? What are the types of streams and classes? Explain in detail.

2.Explain I/O streams with suitable example

Object Oriented Programming: Unit IV: I/O, Generics, String Handling : Tag: : Definition, types with Example Java Programs - Java I/O Stream