[go: up one dir, main page]

0% found this document useful (0 votes)
29 views30 pages

Java I/O Package: Mohasin Sutar C-DAC Mumbai

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 30

Java I/O Package

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

• Contains Classes for File and Directory


Handling
• Contains classes for reading and writing to
streams.
• Object Serialization Classes and
Interfaces
Files
• Most of the classes defined by java.io operate
on streams, the File class does not.
• It deals directly with files and the file system.
That is, the File class does not specify how
information is retrieved from or stored in files; it
describes the properties of a file itself.
• A File object is used to obtain or manipulate
the information associated with a disk file, such
as the permissions, time, date, and directory
path, and to navigate subdirectory hierarchies.
• A directory in Java is treated simply as a File
with one additional property—a list of
filenames that can be examined by the list( )
method.
Files (Contd..)
• The following constructors can be used to create File
objects:
– File(String directoryPath)
– File(String directoryPath, String filename)
– File(File dirObj, String filename)
– File(URI uriObj)
• Instances of File class are immutable
• static fields provide quick access to system-dependent
separators:
File.separator, File.pathSeparator
• ‘/’ works on all platforms, including Windows
Useful File Methods
• isFile/isDirectory
• canRead/canWrite
• length
– Length of the file in bytes (long) or 0 if nonexistent
• list
– If the file object is a directory, returns a String array of all the
files and directories contained in the directory; otherwise, null
• mkdir
– Creates a new subdirectory
• delete
– Deletes the directory and returns true if successful
• boolean renameTo(File newName)
– It will return true upon success and false if the file cannot be
renamed.
• Example
– FileDemo.java
Directories
• A directory is a File that contains a list of other
files and directories. When you create a File
object and it is a directory, the isDirectory( )
method will return true. In this case, you can call
list( ) on that object to extract the list of other
files and directories inside. It has two forms.
– The first is shown here:
String[ ] list( )
The list of files is returned in an array of String objects.
Example: DirList.java
Directories cont…
• Using FilenameFilter:
– You will often want to limit the number of files returned
by the list() method to include only those files that
match a certain filename pattern, or filter. To do this,
you must use a second form of list( ), shown here:
• String[ ] list(FilenameFilter FFObj)
– In this form, FFObj is an object of a class that
implements the FilenameFilter interface.
FilenameFilter defines only a single method, accept( ),
which is called once for each file in a list. Its general
form is given here:
• boolean accept(File directory, String filename)
– The accept( ) method returns true for files in the
directory that should be included in the list (that is,
those that match the filename argument), and returns
false for those files that should be excluded.
– Example: DirListOnly.java
Streams

• 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

Open a stream Open a stream


while more information while more information
read information write information
Close the stream Close the stream

Provided by Provided by
• java.io.InputStream • java.io.OutputStream
• java.io.Reader • java.io.Writer
Byte Streams

• Read and write 8-bit


bytes
• InputStream and
OutputStream are
abstract super
classes
• Typically used to read
and write binary data
such as images and
sounds
Character Streams

• Read and write 16-bit


characters
• Reader and Writer
are the abstract
classes
• Use readers and
writers to read and
write textual
information
Data Streams
• Grouping of classes based on their
purpose is often more convenient rather
their data type, so that streams can be Data Sink Streams
cross-grouped by:
– Whether they read from and write to data
”sinks” or endpoints Character Byte Streams
– Process the information as it is being Streams
read or written
• Bridges from Binary to Character
InputStreamReader,
OutputStreamWriter

InputStream in = openInputStream();
Reader reader = new
InputStreamReader(in, “UTF-8”);

OutputStream out = Processing Streams


openOutputStream();
Writer writer = new
OutputStreamWriter(out, “UTF-8”);
Basic Operations
• Reader and InputStream
– int read() - reads a single byte/character
– int read(byte/char buf[]) - reads as many bytes as possible
into the passed array, returns number of bytes read
– int read(byte/char buf[], int offset, int length) - the same, but
works with the specified portion of an array
-1 is returned when end of file is encountered.
– In addition, both support marking locations within a stream,
skipping input data, and resetting current position
• Writer and OutputStream
– void write(...) methods are analogous with reading
– void flush() - flushes all buffered data to the output (if any)
Opening and Closing

• Streams are automatically opened on creation


– If you have stream instance it is ready for reading and
writing
• Closing is explicit
– close() methods closes the stream.
– flush() is explicit during closing of outputstream.
– Frees all underlying resources
– Is not same as object destruction.
– Always call it as early as possible.
– After close() is called any read or write operation fails.
– Closing several times is safe.
Demo FileInputStream

in

• Copying Bytes from one image


file to another. FileOutputStream

– CopyBytes.java out

• Copying Text from one file to


another.
– CopyCharacters.java FileReader

• Creating String Reader from in

String and store capitalized


string value to file.
– Capitalize.java FileWriter

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

• What is Object Serialization?


– Serialization: process of converting an object’s
representation into a stream of bytes
– Deserialization: reconstituting an object from a
byte stream
– Process of reading and writing objects
– Writing an object is to represent its state in a
serialized form sufficient to reconstruct the object
as it is read.
Basics of Serialization
• Save Object State to Stream.
• Java.io defines two serialization Streams
– ObjectOutputStream for Saving
– ObjectInputStream for restoring
• Create the stream and tell it “Save the Object “
using standard API.
• Why Serialization
– Persistence: Storing Objects in files and Database.
– Marshalling: Passing whole Object between VM’s
over network
• How to make user defined classes Serializable
• Implement java.io.Serializable Interface
– Serializable doesn’t define any methods
– Its Marker Interface.
Saving / Restoring Serializable Object

• 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

You might also like