File Streams & Object Serialization: Advanced Programming

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

File Streams

&
Object Serialization
ADVANCED PROGRAMMING
Lecture 4

Prepared by:
Christopher Panther
Understanding Persistence
• When an object of a class is instantiated
(created), it resides in main memory (RAM) of
the computer on which the program that
created it is running on.
• Normally, as soon as the program terminates,
the objects created by the program are removed
from RAM
2
Understanding Persistence
•Persistence is the ability of an object to
continue existence after the program
that created the object terminates and is
removed from RAM.
•Persistence is achieved by:
•Storing data from an object in a file
•Storing data from an object in a database
3
Understanding Persistence
•Some object-oriented database
management systems (OODBMS) allow
entire objects to be stored and retrieved in
a database through use of object-oriented
programming languages like Java.
•In this unit we will use files to achieve
object persistence
4
File Streams
•A stream is a flow of bytes to or from a
device, a network connection or a file.
•A stream may be one-way such as a
stream associated with an output device
such as a display screen or a stream
associated with an input device such as
a keyboard.
5
File Streams
•A stream may also be multi-directional such as
a stream associated with a file or a network
connection.
•Java provides stream classes which
programmers can use to create stream objects.
•These stream objects can be used to open and
manipulate data in files.
6
File Streams
• Persistence – Maintain data after life of program
• Uses the I/O system of Computer
• File System Maintained by OS
• NTFS (New Technology File System ) Microsoft Windows
• FAT (File Allocation Table)(16/32) Microsoft Windows
Legacy
• EXT3/4 (Third/Fourth Extended Filesystem) UNIX
• HFS+ (Hierarchical File System) Apple Mac OS
7
Streams
•In Programming
• Program -> Destination – (Export / Writing)
• Source -> Program – (Import / Reading)
•Located in java.io package
• Reading Bytes
• Reading Characters

8
Streams
Bytes
• A byte is a group of 8 binary digits (bits)
Fields
• A field is a group of bytes
Records
• A record is a collection of related fields
Files
• A file is a collection of related records
Database
• A database is a collection of related files
9
Input / Output Streams
•I/O done through Streams
•InputStream (Reading data from a source)
•OutputStream (Writing data to a storage
container)

10
Input / Output Streams
•Sequential Access
• Records are stored sequentially
• Records are added (appended) at the end
• Records are always accessed beginning with the
first record, then processed sequentially until the
required record is found or all the records are
processed
• Might be slow for files with large amounts of
records
• File size might be smaller than random access file
12
Input / Output Streams Cont’d
•Random Access
• Requires an initialization phase
• Records are stored in a random manner
• Records can be added anywhere in the file
• The required record can be accessed
immediately without reading other records
• Record deletion requires marking a record as
deleted by overwriting it with null values
14
Input / Output Streams Cont’d
•Random Access
• Can be very fast even for files with large amounts
of records
• File size might be much larger than sequential
access file
• Well-suited for applications where records may
change often and records may need to be
retrieved in a random order, e.g. a parts inventory
system which allows a user to query the price and
description of any item in the inventory.
15
Input / Output Streams Cont’d
• Random Access File Size
• All records must use a fixed amount of memory, variable
length records should not be used
• Determining Memory requirements
• Each data type requires a specific amount of memory
• int 4 bytes
• float 4 bytes
• double 8 bytes
• char 2 bytes – Java
• User defined data types require memory based on the
composition of the data members.
16
Serialized I/O
• Supports the I/O of an entire object – Including
member attributes
• Support the I/O of object graphs
• Composition, Inheritance
• Generics, Collections other Data Structures
• Facilitated through Serializable Interface
• Found in java.io
17
Object Serialization
• Objects may be serialized to
• File Output Streams (Writing) – Object is flattened

• Objects may be deserialized from


• File Input Streams (Reading) – Object is inflated

18
Implementing Serializable
public class Address implements Serializable {
}

public class Staff implements Serializable {


private Address address;
}
19
Implementing Serializable
•Primitive types – Already Implemented
by Java
•Referenced Types – Must Implement
Serializable Interface
•Including Objects in
• Composition
• Data Structures, Generics and Collections
20
Java Serialization Classes
• Serialization (Writing)
• FileOutputStream
• ObjectOutputStream
• Deserialization (Reading)
• FileInputStream
• ObjectInputStream
• All found in java.io package
• Serialization / Deserialization Operations – May Throw
Multiple types of Exceptions
21
Java Serialization Example
• try {
ObjectOutputStream os = new ObjectOutputStream( new
FileOutputStream(“MyDataFile.txt”) );
os.writeObject(staffObj);
os.flush();
os.close();
} catch(Exception ex) {
/*Please note there are multiple exceptions to be handled*/
}

22
Java Deserialization Example
• Staff staffObj = null;
try {
ObjectInputStream is = new ObjectInputStream( new
FileInputStream(“MyDataFile.txt”) );
staffObj = (Staff) is.readObject();
is.close();
} catch(Exception ex) {
/*Please note there are multiple exceptions to be handled*/
}

23
What if we did this?
public class Address {
}
public class Staff implements Serializable {
private Address address;
}

24
Then Did This…
try {
ObjectOutputStream os = new ObjectOutputStream( new
FileOutputStream(“MyDataFile.txt”) );
os.writeObject(staffObj);
os.flush();
os.close();
} catch(Exception ex) {
/*Please note there are multiple exceptions to be handled*/
}
25
Cannot Work!!!
•Address class did not implement
serializable
•Cannot be serialized to be written to file
•NotSerializableException thrown
•May be fixed with “transient”
•Allows Java to ignore non-serialized
reference types
26
Now This Will Work…
public class Address {
}
public class Staff implements Serializable {
private transient Address address;
}

27
Exceptions To Be Handled In Object
Serialization / Deserialization & Streams
• ClassNotFoundException – Java has no definition for class
• ClassCastException – Bad cast when reading from file
• FileNotFoundException – File does not exist
• IOException – Error in File I/O operation
• NotSerializableException – Attempting to serialize class that
did not implement Serializable Interface
• Exception – Generic Exception

28
Questions

29

You might also like