Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 21

Java I/O Streams

Stream
• A stream is an abstract representation of an input and
output device used to read and write data.
Advantages of Streams
• No need to learn inner working of each
device separately.
• The program will work for different input
and output devices without any code
changes.
Types of Stream

1. Byte Stream
2. Character Stream
Types of Stream

• InputStream and OutputStream are designed for byte


streams.

• Reader and Writer are designed for character streams.

1. Use the character stream classes when working with


characters or strings, and
2. Use the byte stream classes when working with bytes or
other binary objects.
Streams
• JAVA distinguishes between 2 types of streams:

• Text – streams, containing ‘characters‘

Program I ‘ M A S T R I N G \n Device

•Binary Streams, containing 8 – bit information


Program 01101001 11101101 00000000 Device
Input and Output Streams
• Output Streams
– When writing data in a stream
– E.g a file, disk etc
• Input Stream
– When read data from a stream
– E.g disk file, the keyboard, or a remote
computer
Buffered Stream
• Transferring data to or from a stream is
extremely inefficient.
• The solution is a BufferedStream.
• A buffer is simply a block of memory that
is used to batch up the data that is
transferred to or from an external device.
Byte Streams
Byte Streams
• When you write data to a binary stream, the data is
written to the stream as a series of bytes.
• Binary numerical values are just written as a series
of bytes
– E.g 4 bytes for int , 8 bytes for long etc.
• Characters are stored internally as Unicode
characters.
– Each is written in binary stream as 2 bytes
Sub Classes of Input Stream Class
Output Stream Class
• The OutputStream class contains three
write() methods for writing binary data to
the stream.
• Mirror the read() methods of the
InputStream class
SubClasses of OutputStream
Character Streams
Character Streams
• Character streams are used for storing and
retrieving text.
• All binary numeric data has to be converted
to a textual representation before being
written to a character stream.
Stream Readers and Writers
• Stream Readers and Writers are objects
that can read and write byte streams as
character streams.
• Reader
• Writer
Reader
• Implements Readable interface
• Methods
– int read()
– int read(char[] cbuf)
Methods of Writer
Using Reader
Using BufferReader
• BufferedReader keyboard = new BufferedReader(new
InputStreamReader(System.in))
Using Writers

You might also like