Input Output Streams IN JAVA
Download
Report
Transcript Input Output Streams IN JAVA
DEPARTMENT OF COMPUTER SCIENCE
N.HARIKA
Contents
•
•
•
•
Overview of I/O Streams
Character Streams
Byte Streams
Using the Streams
2
Overview of I/O Streams
To bring in information, a program opens a
stream on an information source (a file,
memory, a socket) and reads the information
sequentially, as shown in the following figure.
3
Overview of I/O STREAMS Contd.
Similarly, a program can send information to
an external destination by opening a stream to
a destination and writing the information out
sequentially, as shown in the following figure.
4
Overview of I/O streams Contd..
• The java.io package contains a collection of stream
classes that support algorithms for reading and writing.
To use these classes, a program needs to import the
java.io package.
• The stream classes are divided into two class
hierarchies, based on the data type (either characters or
bytes) on which they operate i.e Character Stream and
Byte Stream
5
Character Streams
• Reader and Writer are the abstract super
classes for character streams in java.io.
• Reader provides the API and partial
implementation for readers ( streams that
read 16-bit characters ) and Writer provides
the API and partial implementation for writers
( streams that write 16-bit characters).
6
Character Streams Contd.
• The following figure shows the class
hierarchies for the Reader and Writer classes.
7
Byte Streams
• To read and write 8-bit bytes, programs
should use the byte streams, descendents
of InputStream and OutputStream .
• InputStream and OutputStream provide the
API and partial implementation for input
streams (streams that read 8-bit bytes) and
output streams (streams that write 8-bit
bytes).
8
Byte Streams (cont.)
• These streams are typically used to read and
write binary data such as images and sounds.
• Two of the byte stream classes,
ObjectInputStream and ObjectOutputStream,
are used for object serialization.
9
Byte Streams (cont.)
• The class hierarchy for the Reader Class
10
Byte Stream (cont.)
• Class hierarchy figure for Writer Class
11
How to Use File Streams
The file streams-- FileReader , FileWriter , FileInputStream ,
and FileOutputStream -- read or write from a file on the
native file system.
Here is simple code to create a file reader
File inputFile = new File("farrago.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
This reads characters from the reader as long as there's
more input in the input file and writes those characters to
the writer.
12
How to Use Pipe Streams
• Pipes are used to channel the output from
one thread into the input of another.
PipedReader and PipedWriter (and their
input and output stream counterparts
PipedInputStream and PipedOutputStream
) implement the input and output
components of a pipe.
13
14