W12. Serialization
W12. Serialization
Serialization
1
Objectives
1. To discover how I/O is processed in Java
2. To distinguish between text I/O and binary I/O
3. To store and restore objects using ObjectOutputStream and
ObjectInputStream
4. To implement the Serializable interface to make objects serializable
2
Files
• Files can be classified as either text or binary.
Text File
• A file that can be processed (read, created, or modified) using a text editor is
called a text file.
Binary File
• All files other than text files are called binary files.
For example,
Java source programs are stored in text files and can be read by a text editor,
but Java class files are stored in binary files and are read by the JVM
3
How Is Text I/O Handled in Java?
• File object encapsulates the properties of a file but does not contain the
methods for reading/writing data from/to a file
• In order to perform I/O, objects using appropriate Java I/O classes need to
be created.
• I/O classes can be classified as input classes and output classes.
• FileWriter, BufferedWriter, PrintWriter are output classes
• FileReader, BufferedFileReader, Scanner are input classes
4
How Is Text I/O Handled in Java?
• An input object is also called an input stream and an output object an
output stream
5
Writing in text file
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bufWriter = new BufferedWriter(fileWriter);
bufWriter.write(“ writing a file.");
bufWriter.close();
_________________________________________
PrintWriter output = new PrintWriter("temp.txt");
output.print("Java 101");
output.close();
6
Reading from text file
FileReader fileReader = new FileReader(fileName);
BufferedReader bufReader = new
BufferedReader(fileReader);
while((line = bufReader .readLine()) != null)
{
System.out.println(line);
}
bufReader.close();
_________________________________________
Scanner input = new Scanner(new File("temp.txt"));
System.out.println(input.nextLine());
7
How Is Binary I/O Handled in Java?
• Binary I/O does not involve encoding or decoding and thus is more
efficient than text I/O
• All files are stored in binary format, and thus all files are essentially binary
files.
• Text I/O is built upon binary I/O to provide a level of abstraction for
character encoding and decoding
• The JVM converts Unicode to a file-specific encoding when writing a
character, and it converts a file-specific encoding to Unicode when reading
a character
• . Binary files are independent of the encoding scheme on the host
machine and thus are portable.
• Java programs on any machine can read a binary file created by a Java
program.
8
Text I/O vs. Binary I/O
Text I/O requires encoding and decoding, whereas binary I/O does not
9
Binary I/O Classes
10
FileInputStream/FileOutputStream
• FileInputStream/FileOutputStream is for reading/writing bytes from/to files.
• To construct a FileOutputStream, use the constructors
FileOutputStream(file: File).
• If the file does not exist, a new file will be created.
• If the file already exists, the first two constructors will delete the current
content of the file.
• To retain the current content and append new data into the file, use the last
two constructors and pass true to the append parameter
11
Writing in binary file
FileOutputStream output = new FileOutputStream("temp.dat");
for (int i = 1; i <= 10; i++)
output.write(i);
output.close();
12
Reading from binary file
FileInputStream input = new FileInputStream("temp.dat");
int value;
input.close();
When a stream is no longer needed, always close it using the close() method. Not
closing streams may cause data corruption in the output file, or other programming
errors.
13
Object I/O
• ObjectInputStream/ObjectOutputStream classes can be used to read/write
serializable objects
• ObjectInputStream/ObjectOutputStream perform I/O for objects
• ObjectInputStream/ObjectOutputStream perform I/O for primitive type
values, and strings
14
Object I/O
ObjectInputStream
ObjectOutputStream
15
ObjectOutputStream
16
ObjectInputStream
17
Serialization
• Serialization in java is a mechanism of writing the state of an object into a
byte stream.
• An object can be represented as a sequence of bytes (that includes the
object's data as well as information about the object's type and the types
of data stored in the object) in the file. This mechanism is called Object
Serialization
• Java provides a built-in mechanism to automate the process of writing
objects
Deserialization
• The reverse operation of serialization is called deserialization.
• An Object can be read from the file, the type information and bytes that
represent the object and its data can be used to recreate the object in
memory. This mechanism is called Object Deserialization
18
Serialization
• JVM independent
• Classes ObjectInputStream and ObjectOutputStream contain the
methods for serializing and deserializing an object.
• ObjectOutputStream is used to write object in the memory, while
ObjectInputStream is used to read object from the memory
writeObject(Object x)
readObject()
• Not every object can be written to an output stream. Objects that can be
so written are said to be serializable.
19
The Serializable Interface
• A serializable object is an instance of the java.io.Serializable interface, so
the object’s class must implement Serializable.
• It is a marker interface, it has no methods
• It enables the Java serialization mechanism to automate the process of
storing objects and arrays
• Example:
– Date class
– Swing GUI component classes
• Class of the serializable object is encoded
• If a class implements serializable then all its sub classes will also be
serializable
20
The Serializable Interface
• Static variable cannot be serialized
• Nonserializable instance data fields of a class cannot be serialized.
• If a field is not serializable, it must be marked transient.
21
The Serializable Interface
• If an object is written to an object stream more than once, It will not
stored multiple copies.
• A serial number is created for each object but for duplicate object, their
references will be the same
Serializing Arrays
• An array is serializable if all its elements are serializable.
• An entire array can be saved into a file using writeObject and later can be
restored using readObject
22
Object Serialization
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
______________________________________________
OutSt.writeObject(studentObject);
OutSt.flush();
23
Object Deserialization
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
______________________________________________
24