Unit III , Chapter 2
OOP using Java Programming Language Input
and Output ( IO) Streams
[Link] Pratap
Assistant Professor, CSE Department
pratapadimulam@[Link]
17CS3302 OOPs using Java Section - C
Overview
IO Streams Fundamentals. FileReader.
Byte Streams. FileWriter.
Input Streams.
Output Streams.
FileInputStream.
FileOutputStream.
Character Streams.
Reader.
Writer.
[Link] Pratap , Asst. Professor, CSE Department 2
17CS3302 OOPs using Java Section - C
Introduction
So far we have used variables and arrays for storing data inside
the programs. This approach poses the following limitations:
The data is lost when variable goes out of scope or when the program
terminates. That is data is stored in temporary/mail memory is
released when program terminates.
It is difficult to handle large volumes of data.
We can overcome this problem by storing data on secondary
storage devices such as floppy or hard disks.
The data is stored in these devices using the concept of Files and
such data is often called persistent data.
[Link] Pratap , Asst. Professor, CSE Department 3
17CS3302 OOPs using Java Section - C
File Processing
Storing and manipulating data using files is known as file
processing.
Reading/Writing of data in a file can be performed at the
level of bytes, characters, or fields depending on
application requirements.
Java also provides capabilities to read and write class
objects directly. The process of reading and writing objects
is called object serialisation.
[Link] Pratap , Asst. Professor, CSE Department 4
17CS3302 OOPs using Java Section - C
I/O and Data Movement
The flow of data into a program
(input) may come from different
devices such as keyboard, mouse,
memory, disk, network, or
another program.
The flow of data out of a
program (output) may go to the
screen, printer, memory, disk,
network, another program.
Both input and output share a
certain common property such
as unidirectional movement of
data – a sequence of bytes and
characters and support to the
sequential access to the data.
[Link] Pratap , Asst. Professor, CSE Department 5
17CS3302 OOPs using Java Section - C
Streams Fundamentals
Java Uses the concept of Streams to
represent the ordered sequence of data,
a common characteristic shared by all
I/O devices.
Streams presents a uniform, easy to
use, object oriented interface between
the program and I/O devices.
A stream in Java is a path along which
data flows (like a river or pipe along
which water flows).
[Link] Pratap , Asst. Professor, CSE Department 6
17CS3302 OOPs using Java Section - C
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.
[Link] Pratap , Asst. Professor, CSE Department 7
17CS3302 OOPs using Java Section - C
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.
[Link] Pratap , Asst. Professor, CSE Department 8
17CS3302 OOPs using Java Section - C
The Data Hierarchy
Lowest level of data storage is in binary digits
0s and 1s -- bits
Bits grouped together into bytes
Bytes grouped into characters
Characters and/or bytes grouped together to form
fields
Fields grouped together to form records
Records grouped to form files
[Link] Pratap , Asst. Professor, CSE Department 9
17CS3302 OOPs using Java Section - C
Contd.
[Link] Pratap , Asst. Professor, CSE Department 10
17CS3302 OOPs using Java Section - C
Types of Streams
The concepts of sending data
from one stream to another (like
a pipe feeding into another pipe) Input Stream
has made streams powerful tool reads
for file processing. Source Program
Connecting streams can also act Output Stream
as filters.
Program Destination
Streams are classified into two writes
basic types:
Input Steam
Output Stream
[Link] Pratap , Asst. Professor, CSE Department 11
17CS3302 OOPs using Java Section - C
Input Stream and Output Stream
Java application uses an Input Stream to read data from a source,
it may be a file, an array, peripheral device, socket.
Java application uses an Output Stream to write data to a
destination, it may be a file, an array, peripheral device or socket.
[Link] Pratap , Asst. Professor, CSE Department 12
17CS3302 OOPs using Java Section - C
Java Stream Classes
Input/Output related classes are defined in [Link]
package.
Input/Output in Java is defined in terms of streams.
A stream is a sequence of data, of no particular length.
Java classes can be categorised into two groups based
on the data type one which they operate:
Bytestreams
Character Streams
[Link] Pratap , Asst. Professor, CSE Department 13
17CS3302 OOPs using Java Section - C
Contd.
[Link] Pratap , Asst. Professor, CSE Department 14
17CS3302 OOPs using Java Section - C
[Link] Pratap , Asst. Professor, CSE Department 15
17CS3302 OOPs using Java Section - C
Contd.
[Link] Pratap , Asst. Professor, CSE Department 16
17CS3302 OOPs using Java Section - C
Streams
Byte Streams Character streams
Operated on 8 bit (1 byte) Operates on 16-bit (2
data. byte) unicode
characters.
Input streams/Output Readers/ Writers
streams
[Link] Pratap , Asst. Professor, CSE Department 17
17CS3302 OOPs using Java Section - C
Classification of Java IO Stream Classes
[Link] Pratap , Asst. Professor, CSE Department 18
17CS3302 OOPs using Java Section - C
Byte Input Stream Classes
[Link] Pratap , Asst. Professor, CSE Department 19
17CS3302 OOPs using Java Section - C
Byte Input Streams - Methods
Useful Methods Description
public abstract int read() Reads a byte and returns as a
integer 0-255
public int read(byte[] buf, int Reads and stores the bytes in
offset, int count) buf starting at offset. Count is
the maximum read.
public int read(byte[] buf) Same as previous offset=0
and length=[Link]()
public long skip(long count) Skips count bytes.
public int available() Returns the number of bytes
that can be read.
public void close() Closes stream
[Link] Pratap , Asst. Professor, CSE Department 20
17CS3302 OOPs using Java Section - C
FileInputStream Class and its Methods
Java FileInputStream class obtains input bytes from a file. It is
used for reading byte-oriented data (streams of raw bytes) such
as image data, audio, video etc.
Syntax: FileInputStream fis=new FileInputStream(“[Link]”);
Methods:
Method Description
int available() It is used to return the estimated number of bytes that
can be read from the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to [Link] bytes of data from the
input stream.
int read(byte[] b, int off, int len) It is used to read up to len bytes of data from the input
stream.
long skip(long x) It is used to skip over and discards x bytes of data from
the input stream.
[Link] Pratap , Asst. Professor, CSE Department 21
17CS3302 OOPs using Java Section - C
FileInputStream- example
Count total number of bytes in the file
import [Link].*;
class CountBytes {
public static void main(String[] args) throws FileNotFoundException, IOException
{
FileInputStream in;
in = new FileInputStream(“[Link]”);
int total = 0;
while ([Link]() != -1)
total++;
[Link](total + “ bytes”);
}
}
[Link] Pratap , Asst. Professor, CSE Department 22
17CS3302 OOPs using Java Section - C
What happens if the file did not exist
JVM throws exception and terminates the program since there
is no exception handler defined.
[pratap] Streams [1:165] java CountBytes
RUNTIME ERROR [ FileNotFoundException ]
Exception in thread "main" [Link]: [Link] (No
such file or directory)
at [Link](Native Method)
at [Link].<init>([Link])
at [Link]([Link])
[Link] Pratap , Asst. Professor, CSE Department 23
17CS3302 OOPs using Java Section - C
Byte Output Streams
[Link] Pratap , Asst. Professor, CSE Department 24
17CS3302 OOPs using Java Section - C
Byte Output Streams - Methods
Useful Methods Description
public abstract void write(int b) Write b as bytes.
public void write(byte[] buf, int Write count bytes starting
offset, int count) from offset in buf.
public void write(byte[] buf) Same as previous offset=0
and count = [Link]()
public void flush() Flushes the stream.
public void close() Closes stream
[Link] Pratap , Asst. Professor, CSE Department 25
17CS3302 OOPs using Java Section - C
FileOutputStream Class and its Methods
Java FileOutputStream is an output stream used for writing data
to a [Link] you have to write primitive values into a file, use
FileOutputStream class.
Syntax: FileOutputStream fos=new FileOutputStream(“[Link]”);
Methods:
Method Description
protected void finalize() It is used to clean up the connection with the file
output stream.
void write(byte[] ary) It is used to write [Link] bytes from the byte
array to the file output stream.
void write(byte[] ary, int off, int len) It is used to write len bytes from the byte array
starting at offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file
output stream.
[Link] Pratap , Asst. Professor, CSE Department 26
17CS3302 OOPs using Java Section - C
FileOutputStream - example
Read from standard in and write to standard out
import [Link];
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream(“[Link]”);
String s="Welcome to IO Streams";
byte b[]=[Link]();//converting string into byte array
[Link](b);
[Link]();
[Link]("success...");
}catch(Exception e){[Link](e);}
}
}
[Link] Pratap , Asst. Professor, CSE Department 27
17CS3302 OOPs using Java Section - C
File Handling in Java
There are 2 ways of initialising file stream objects:
Passing file name directly to the stream constructor
Similar to previous example
Passing File Object:
Create File Object
File inFile = new File("[Link]");
Pass file object while creating stream:
try {
in = new FileInputStream(inFile);
}
Manipulation operations are same once the file is
opened.
[Link] Pratap , Asst. Professor, CSE Department 28
17CS3302 OOPs using Java Section - C
Character Input and Output Streams
Character stream classes can be used to read and write
16 bit Unicode characters.
Reader Stream class: Used to read characters from file.
These are functionally same as InputStream classes but
these read characters instead of bytes.
Writer Stream class: Used to write characters to file.
These are functionally same as OutputStream classes but
these write characters instead of bytes.
[Link] Pratap , Asst. Professor, CSE Department 29
17CS3302 OOPs using Java Section - C
Reader Classes Hierarchy
[Link] Pratap , Asst. Professor, CSE Department 30
17CS3302 OOPs using Java Section - C
Reader classes – Useful Methods
Useful Methods Description
public int read() Reads a character and returns as a integer
0-255
public int read(char[] buf, int offset, Reads and stores the characters in buf
int count) starting at offset. count is the maximum
read.
public int read(char[] buf) Same as previous offset=0 and
length=[Link]()
public long skip(long count) Skips count characters.
public boolean available() Returns true if the stream is ready to be
read.
public void close() Closes stream
[Link] Pratap , Asst. Professor, CSE Department 31
17CS3302 OOPs using Java Section - C
FileReader Class and its Methods
Java FileReader class is used to read data in characters from the
file.
Syntax: FileReader fr=new FileReader(“[Link]”);
Methods:
Method Description
int read() It is used to return a character in ASCII
form. It returns -1 at the end of file.
void close() It is used to close the FileReader class.
[Link] Pratap , Asst. Professor, CSE Department 32
17CS3302 OOPs using Java Section - C
FileReader - example
Count total number of spaces in the file
import [Link].*;
public class CountSpace {
public static void main (String[] args)
throws IOException
{
Reader in; // in can also be FileReader
in = new FileReader("[Link]");
int ch, total, spaces;
spaces = 0;
for (total = 0 ; (ch = [Link]()) != -1; total++){
if([Link]((char) ch))
{
spaces++;
}
}
[Link](total + " chars " + spaces + " spaces ");
}
}
[Link] Pratap , Asst. Professor, CSE Department 33
17CS3302 OOPs using Java Section - C
Writer Classes Hierarchy
[Link] Pratap , Asst. Professor, CSE Department 34
17CS3302 OOPs using Java Section - C
Byte Output Streams - operations
public abstract void write(int Write ch as characters.
ch)
public void write(char[] buf, int Write count characters starting
offset, int count) from offset in buf.
public void write(char[] buf) Same as previous offset=0 and
count = [Link]()
public void write(String str, int Write count characters starting
offset, int count) at offset of str.
public void flush() Flushes the stream.
public void close()
[Link] Pratap , Asst. Professor, CSE Department
Closes stream 35
17CS3302 OOPs using Java Section - C
Copying Characters from Files
Write a Program that copies contents of a source file to a destination file.
The names of source and destination files is passed as command line arguments.
Make sure that sufficient number of arguments are passed.
Print appropriate error messages.
[Link] Pratap , Asst. Professor, CSE Department 36
17CS3302 OOPs using Java Section - C
[Link]
import [Link].*;
public class FileCopy { int ch;
while((ch=[Link]()) != -1)
public static void main (String[] args) [Link](ch);
{ [Link]();
if([Link] != 2) [Link]();
{ }
[Link]("Error: in catch(IOException e)
sufficient arguments");
{
[Link]("Usage - java
FileCopy SourceFile DestFile"); [Link](e);
[Link](-1); [Link](-1);
} }
try { }
FileReader srcFile = new FileReader(args[0]); }
FileWriter destFile = new
FileWriter(args[1]);
[Link] Pratap , Asst. Professor, CSE Department 37
17CS3302 OOPs using Java Section - C
Buffered Streams
Java supports creation of buffers to store temporarily data that
read from or written to a stream. This process is known as
buffered I/O operation.
Buffered stream classes – BufferedInputStream,
BufferedOutputStream, BufferedReader, BufferedWriter buffer
data to avoid every read or write going to the stream.
These are used in file operations since accessing the disk for
every character read is not efficient.
[Link] Pratap , Asst. Professor, CSE Department 38
17CS3302 OOPs using Java Section - C
Contd.
Buffered character streams understand lines of text.
BufferedWriter has a newLine method which writes a
new line character to the stream.
BufferedReader has a readLine method to read a line of
text as a String.
For complete listing of methods, please see the Java
manual/documentation.
[Link] Pratap , Asst. Professor, CSE Department 39
17CS3302 OOPs using Java Section - C
BufferedReader - example
Use a BufferedReader to read a file one line at a time and print
the lines to standard output
import [Link].*;
class ReadTextFile {
public static void main(String[] args)
throws FileNotFoundException, IOException
{
BufferedReader in;
in = new BufferedReader( new FileReader(“[Link]”));
String line;
while (( line = [Link]()) != null )
{
[Link](line);
}
}
}
[Link] Pratap , Asst. Professor, CSE Department 40
17CS3302 OOPs using Java Section - C
Handling Primitive Data Types
The basic input and output streams provide read/write
methods that can be used for reading/writing bytes or
characters.
To read/write the primitive data types such as integers and
doubles, we can use filter classes as wrappers on the existing
I/O streams to filter data to the original stream.
The two filter classes supported for creating “data streams”
for primitive data types are:
DataInputStream
DataOutputStream
[Link] Pratap , Asst. Professor, CSE Department 41
17CS3302 OOPs using Java Section - C
Hierarchy of Data Stream Classes
Class Interface
FilterInputStream DataInput
DataInputStream
Class Interface
FilterOutputStream DataOutput
DataOutputtStream
[Link] Pratap , Asst. Professor, CSE Department 42
17CS3302 OOPs using Java Section - C
Data Input Streams
Create Input File Stream:
FileInputStream fis = new FileInputStream(“InFile”);
Create Input Data Stream:
DataInputStream dis = new DataInputStream( fis );
The above statements wrap data input stream (dis) on file input
stream (fis) and use it as a “filter”.
Methods Supported:
readBoolean(), readByte(), readChar(), readShort(), readInt(),
readLong(), readFloat(), readDouble()
They read data stored in file in binary format.
[Link] Pratap , Asst. Professor, CSE Department 43
17CS3302 OOPs using Java Section - C
Data Output Stream classes
Create Output File Stream:
FileOutputStream fos = new FileOutputStream(“OutFile”);
Create Output Data Stream:
DataOutputStream dos = new DataOutputStream( fos );
The above statements wrap data output stream (dos) on file output
stream (fos) and use it as a “filter”.
Methods Supported:
writeBoolean(), writeByte(), writeChar(), writeShort(),
writeInt(), writeLong(), writeFloat(), writeDouble()
They write data to file in binary format.
How many bytes are written to file when for statements:
writeInt(120), writeInt(10120)
[Link] Pratap , Asst. Professor, CSE Department 44
17CS3302 OOPs using Java Section - C
Summary
All Java I/O classes are designed to operate with
Exceptions.
User Exceptions and your own handler with files to
manger runtime errors.
Subclasses FileReader / FileWriter support
characters-based File I/O.
FileInputStream and FileOutputStream classes
support bytes-based File I/O.
Buffered read operations support efficient I/O
operations.
[Link] Pratap , Asst. Professor, CSE Department 45
17CS3302 OOPs using Java Section - C
Summary
Streams provide uniform interface for managing I/O operations
in Java irrespective of device types.
Java supports classes for handling Input Streams and Output
streams via [Link] package.
Exceptions supports handling of errors and their propagation
during file operations.
[Link] Pratap , Asst. Professor, CSE Department 46