Java I/O Package: Mohasin Sutar C-DAC Mumbai
Java I/O Package: Mohasin Sutar C-DAC Mumbai
Java I/O Package: Mohasin Sutar C-DAC Mumbai
Mohasin Sutar
C-DAC Mumbai
Topics to be Covered
• The java.io.package
• Files
• Byte Streams and Unicode Character
Streams.
• Persistence of Objects
• Object Serialization Methods
Introduction
• What is I/O ?
– Communication between computer and
outside world.
– What is Outside World
• Human Users
• Other Computers and Programs
• I/O in Computer Programs
– Communication with Hardware devices
• Monitors, Keyboards, Disk Drives
Need of I/O Operations
• Essential part of Most programs
• Computers spend lots of time performing
nothing but I/O operations
• Can be complicated.
• Performance Killer.
• Advantages of file I/O
– Permanent copy
– Output from one program can be input to
another
– Input can be automated.
java.io package
• An abstraction of the
continuous one-way of data
• Reading and Writing is bytes bytes
possible using streams.
• Streams are either
byte-oriented or
character-oriented
• An IOException may occur
during any IO operation
010011001 010011001
Stream Class
• Java’s stream-based I/O is built upon four abstract
classes: InputStream, OutputStream, Reader, and
Writer.
• InputStream and OutputStream are designed for
byte streams.
• Reader and Writer are designed for character
streams.
• In general, you should use the character stream
classes when working with characters or strings,
and use the byte stream classes when working with
bytes or other binary objects.
Basic I/O Algorithm
• Reading • Writing
Provided by Provided by
• java.io.InputStream • java.io.OutputStream
• java.io.Reader • java.io.Writer
Byte Streams
InputStream in = openInputStream();
Reader reader = new
InputStreamReader(in, “UTF-8”);
in
– CopyBytes.java out
out
Buffer Streams
• Buffer data while reading or writing, thereby reducing the
number of accesses required on the original data source.
• More efficient than similar non-buffered streams
• Buffered input streams read data from a memory area
known as a buffer. The native input API is called only
when the buffer is empty
• Buffered output streams write data to a buffer, and the
native output API is called only when the buffer is full.
• A program can convert an unbuffered stream into a
buffered stream using the wrapping.
input = new BufferedReader(new FileReader(“src.txt"));
output = new BufferedWriter(new FileWriter(“dest.txt"));
BufferedReader BufferedInputStream
BufferedWriter BufferedOutputStream
Character Streams Byte Streams
PrintWriter and PrintStream
• Easiest streams containing high level printing
methods (print, println) to write
• Can be created so as to flush automatically
• PrintStream
– Adds functionality to another output stream,
namely the ability to print representations of
various data values conveniently
– Flush automatically
– All characters printed by a PrintStream are
converted into bytes using the platform's default
character encoding
• Demo
– PrintStreamDemo.java and PrintWriterDemo.java
Conversion Streams
• InputStreamReader
– Reads bytes and translate them into character
streams using the specified char set
– Can be wrapped within a BufferedReader for
efficiency
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
System.in BufferedReader (in)
InputStreamReader
Conversion Streams
• OutputStreamWriter
– Writes character to an output stream translating into
bytes
– Can be wrapped within a BufferedWriter for efficiency
OutputStreamWriter outWriter =
new OutputStreamWriter(System.out);
Bufferedwriter out =
new Bufferedwriter(outWriter);
System.out BufferedWriter (out)
OutputStreamWriter
Persistence of Objects
• Object durability, or persistence, is the term you often
hear used in conjunction with storing objects.
• One of the most critical tasks that applications have to
perform is to save and restore data.
• First, the programmer must create a specification
document for the proposed file structure for storing
object.
• Next, the programmer must implement save and restore
functions that convert object data to & from primitive data
types.
• If Object parameters changes, the file specification must
be modified, as well as the save and restore methods
• The solution to this is object serialization.
Object Serialization
• Writing • Reading
• Create an • Create an
ObjectInputStream from
ObjectOutputStream
any input stream
from any output stream
• Use method
• Use Object readObject()
writeObject(Object obj) • Returned type must be
• Handle downcast to actual type
– IOException, • Handle
– NotSerializableException – IOException
– InvalidClassException – ClassNotFoundException
Serializing Objects
• How to Write to an • How to Read from an
ObjectOutputStream ObjectOutputStream
– Writing objects to a stream is – Example that reads in the
a straight-forward process. String and the Date object
Example of constructing a that was written to the file
Date object and then named theTime in the read
serializing that object: example:
FileOutputStream out = new
FileInputStream in = new
FileOutputStream("theTime");
FileInputStream("theTime");
ObjectOutputStream s = new
ObjectOutputStream(out); ObjectInputStream s = new
ObjectInputStream(in);
String today =
s.writeObject("Today"); (String)s.readObject();
s.writeObject(new Date()); Date date =
s.flush(); (Date)s.readObject();
Serialization - Points to Remember
• An object is default-serializable if all the non-static, non-
transient data members are serializable.
– An object can easily inherit “serializability”
• Anonymous Inner classes can not be serialized.
• There may be time when we want to serialize an object,
but omit certain key features, like passwords or other
sensitive data.
• Even objects and data identified as private get serialized.
• Solution: use the transient keyword:
private transient String password = “123$%^.”;
• Member variable identified as transient are not
serialized.
Serialization and Class Versioning
• 64-bit fingerprint (serialVersionUID) for the class is
calculated
• When object is read from an object stream, system
ensures that version UIDs of ObjectStreamClass and
local class are the same.
• If not, java.io.InvalidClassException exception is
thrown
• Add following line to the class
static final long serialVersionUID = /*some long
integer*/;
• Why Class Versioning
– It prevents nasty bugs that might appear if two versions of a
class were truly incompatible in some way