SlideShare a Scribd company logo
By – Gulshan kushwaha
. Serialization in Java : Java Serialization is the mechanism in
which the state of an object is converted to a byte stream so
that the byte stream can be reverted back into the copy of the
object written into a file or stored into a database. It includes
information about object’s type and types of data stored in the
object.
Once the object is serialized into written into a file, it can be
read from the file and deserialized which means that the type of
information and bytes that represent the object can be utilized
to create object in the memory
Copyright @ 2015 Learntek. All Rights Reserved. 3
Let’s understand streams in computer systems before proceeding
further. A stream is simply a sequence of data elements. Data in
the form of streams is generated from a source and consumed at
a destination.
Different data streams in the computer systems are:
1. Byte Stream – It is a low level I/O operation and does not have
any encoding scheme. The Java program should have a buffered
approach for I/O operations to process Byte Stream.
Copyright @ 2015 Learntek. All Rights Reserved. 4
2. Data Stream – Data Stream allows to read-write primitive
data types and used to perform binary I/O operations on
primitive data types. I/O operations can be performed for byte,
char, boolean, short, int, long, float, double and strings
efficiently and conveniently.
3. Character Stream – The character stream can easily
translate to and from local character set unlike byte stream. It
has a proper encoding scheme such as UNICODE, ASCII and
is composed of streams of characters. In Java UNICODE
system is followed to store characters as character stream.
Copyright @ 2015 Learntek. All Rights Reserved. 5
4. Object Stream – Object stream can covert the state of an
object into a byte stream so that it can be stored into
a database, file or transported to any location (Serialization)
and used at a later point of time for retrieving the stored
values and restoring the old state of the object.
The process of serialization is instance independent which
means an object can be serialized on one platform and
deserialized on an entirely different platform. To make an
object serializable we use java.io.Serializable interface.
Copyright @ 2015 Learntek. All Rights Reserved. 6
Both the classes Object Input Stream and Object Output
Stream are high-level streams and extend java.io.InputStream
and java.io.OutputStream.
The ObjectOutputStream has many write methods for writing
different data types. One of the popular write method in
ObjectOutputStream is:
This method serializes an object and converts it into stream of
bytes and sends it to output stream. The popular method to
read an object in ObjectInputStream is:
Copyright @ 2015 Learntek. All Rights Reserved. 7
This method reads the stream of bytes and converts it
back to an object which is called deserialization.
Java Serialization API contains methods for serialization
and deserialization. A class must implement
java.io.Serializable interface to serialize an object.
Let’s understand the concept of Serialization with the
help of an example.
Copyright @ 2015 Learntek. All Rights Reserved. 8
package com.serialization;import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;public class SerializationDemoExample {
/**
* The method will read data from file for deSerialization.
* @param file
* @return
* @throws IOException
* @throws ClassNotFoundException
*/public static Object deSerialize(String file) throws IOException, ClassNotFoundException {
FileInputStream fileInputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
ObjectInputStream objectInputStream = new ObjectInputStream(bufferedInputStream);
Object object = objectInputStream.readObject();
objectInputStream.close();
return object;
}/**
* The method writes data to file for Serialization.
* @param file
* @param object
* @throws IOException
*/public static void serialize(String file, Object object) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(bufferedOutputStream);
objectOutputStream.writeObject(object);
objectOutputStream.close();
}
}
Copyright @ 2015 Learntek. All Rights Reserved. 9
This class defines two methods – deserialize and serialize.
In the deSerialize method the path and file name of the file is
called. This file contains the byte stream of object’s state. Once
the file name and path are called the deSerialize method returns
the object that can be down casted to the corresponding serialized
class object. During deSerialize method we open the file in read
mode using FileInputStream class and pass the object to
BufferedInputStream class constructor. The object is then passed
to the constructor class ObjectInputStream while instantiating. In
ObjectInputStream class we call the readObject() method which
will carry out the actual deserialization.
Copyright @ 2015 Learntek. All Rights Reserved. 10
In the serialize method there are two parameters i.e., file
path & name and data object which is required to be
serialized. In this method we first open the file in write
mode using FileOutputStream class and pass the object
to BufferedOutputStream class constructor. Then the
object is passed to ObjectOutputStream class while
instantiating and writeObject() method is called to
serialize the data object and write byte stream into
opened file.
Copyright @ 2015 Learntek. All Rights Reserved. 11
There are certain fields in the class of an object which
you may not want to serialize such as sensitive
information (keys, password, etc.). We protect those
fields from getting saved during the process of
serialization. Using the keyword transient before any
field of an object won’t get serialized since transient
objects are not eligible for serialization. When
deserialized the value of these transient fields will have
the default value.
Copyright @ 2015 Learntek. All Rights Reserved. 12
package com.serialization;
import java.io.IOException;
public class SerializationImplDemo {
public static void main(String args[]) {
DataObject dataObject = new DataObject();
dataObject.setClient(“Yolanda”);
dataObject.setStore(“Programming store”);
dataObject.setId(“hhhhh”);
dataObject.setPasswordKeys(“$MyG0tt!!”);
try {
SerializationDemoExample.serialize(“file.txt”, dataObject);
DataObject object = (DataObject)
SerializationDemoExample.deSerialize(“file.txt”);
System.out.println(object.toString());
} catch (IOException exp) {
exp.printStackTrace();
} catch (ClassNotFoundException exp) {
exp.printStackTrace();
}
}
}
Copyright @ 2015 Learntek. All Rights Reserved. 13
package com.serialization;
import java.io.Serializable;
public class DataObject implements Serializable{
private static final long serialVersionUID = 1L;
private String client;
private String store;
transient private String id;
transient private String passwordKeys;
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public String getStore() {
return store;
}
public void setStore(String store) {
this.store = store;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPasswordKeys() {
return passwordKeys;
}
public void setPasswordKeys(String passwordKeys) {
this.passwordKeys = passwordKeys;
}
@Override
public String toString() {
String result = “client : ” + client + “nstore : ” + store + “nID : ” + id
+ “npasswordKeys : ” + passwordKeys;
return result;
}
}
Serialization in Java Example 3 : DataObject.java
Copyright @ 2018 Learntek. All Rights Reserved. 14
Thank you

More Related Content

Similar to Gulshan serialization inJava PPT ex.pptx

Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
Victer Paul
 
09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP
Nguyen Tuan
 
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & OutputItp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Outputphanleson
 
Session 22 - Java IO, Serialization
Session 22 - Java IO, SerializationSession 22 - Java IO, Serialization
Session 22 - Java IO, Serialization
PawanMM
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization
Hitesh-Java
 
Unit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptxUnit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptx
DrYogeshDeshmukh1
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301
ArthyR3
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
PRN USM
 
1.26 File Input-Output in JAVA.pptx
1.26 File Input-Output in JAVA.pptx1.26 File Input-Output in JAVA.pptx
1.26 File Input-Output in JAVA.pptx
YashrajMohrir
 
Eclipse Day India 2011 - Extending JDT
Eclipse Day India 2011 - Extending JDTEclipse Day India 2011 - Extending JDT
Eclipse Day India 2011 - Extending JDTdeepakazad
 
Java I/O and Object Serialization
Java I/O and Object SerializationJava I/O and Object Serialization
Java I/O and Object Serialization
Navneet Prakash
 
Basic of Javaio
Basic of JavaioBasic of Javaio
Basic of Javaio
suraj pandey
 
File Input and Output in Java Programing language
File Input and Output in Java Programing languageFile Input and Output in Java Programing language
File Input and Output in Java Programing language
BurhanKhan774154
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsDon Bosco BSIT
 
L04 base patterns
L04 base patternsL04 base patterns
L04 base patterns
Ólafur Andri Ragnarsson
 
Serialization/deserialization
Serialization/deserializationSerialization/deserialization
Serialization/deserialization
Young Alista
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
SPTechCon
 
Java Basics
Java BasicsJava Basics
Java Basics
shivamgarg_nitj
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
SudhanshiBakre1
 
Java program file I/O
Java program file I/OJava program file I/O
Java program file I/O
Nem Sothea
 

Similar to Gulshan serialization inJava PPT ex.pptx (20)

Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP
 
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & OutputItp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
 
Session 22 - Java IO, Serialization
Session 22 - Java IO, SerializationSession 22 - Java IO, Serialization
Session 22 - Java IO, Serialization
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization
 
Unit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptxUnit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptx
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
1.26 File Input-Output in JAVA.pptx
1.26 File Input-Output in JAVA.pptx1.26 File Input-Output in JAVA.pptx
1.26 File Input-Output in JAVA.pptx
 
Eclipse Day India 2011 - Extending JDT
Eclipse Day India 2011 - Extending JDTEclipse Day India 2011 - Extending JDT
Eclipse Day India 2011 - Extending JDT
 
Java I/O and Object Serialization
Java I/O and Object SerializationJava I/O and Object Serialization
Java I/O and Object Serialization
 
Basic of Javaio
Basic of JavaioBasic of Javaio
Basic of Javaio
 
File Input and Output in Java Programing language
File Input and Output in Java Programing languageFile Input and Output in Java Programing language
File Input and Output in Java Programing language
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io Streams
 
L04 base patterns
L04 base patternsL04 base patterns
L04 base patterns
 
Serialization/deserialization
Serialization/deserializationSerialization/deserialization
Serialization/deserialization
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
 
Java Basics
Java BasicsJava Basics
Java Basics
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
Java program file I/O
Java program file I/OJava program file I/O
Java program file I/O
 

Recently uploaded

Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
MuhammadTufail242431
 
LIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.pptLIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.ppt
ssuser9bd3ba
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
calpeda Water Efficient and Effective Pump.pptx
calpeda Water Efficient and Effective Pump.pptxcalpeda Water Efficient and Effective Pump.pptx
calpeda Water Efficient and Effective Pump.pptx
calpedapumpindia
 
İTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering WorkshopİTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering Workshop
Emre Günaydın
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
Kamal Acharya
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
Scaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltageScaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltage
RCC Institute of Information Technology
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Toll tax management system project report..pdf
Toll tax management system project report..pdfToll tax management system project report..pdf
Toll tax management system project report..pdf
Kamal Acharya
 
Top 13 Famous Civil Engineering Scientist
Top 13 Famous Civil Engineering ScientistTop 13 Famous Civil Engineering Scientist
Top 13 Famous Civil Engineering Scientist
gettygaming1
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
Explosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdfExplosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdf
884710SadaqatAli
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
abh.arya
 
Online resume builder management system project report.pdf
Online resume builder management system project report.pdfOnline resume builder management system project report.pdf
Online resume builder management system project report.pdf
Kamal Acharya
 

Recently uploaded (20)

Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
 
LIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.pptLIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.ppt
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
calpeda Water Efficient and Effective Pump.pptx
calpeda Water Efficient and Effective Pump.pptxcalpeda Water Efficient and Effective Pump.pptx
calpeda Water Efficient and Effective Pump.pptx
 
İTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering WorkshopİTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering Workshop
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
Scaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltageScaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltage
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Toll tax management system project report..pdf
Toll tax management system project report..pdfToll tax management system project report..pdf
Toll tax management system project report..pdf
 
Top 13 Famous Civil Engineering Scientist
Top 13 Famous Civil Engineering ScientistTop 13 Famous Civil Engineering Scientist
Top 13 Famous Civil Engineering Scientist
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
Explosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdfExplosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdf
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
 
Online resume builder management system project report.pdf
Online resume builder management system project report.pdfOnline resume builder management system project report.pdf
Online resume builder management system project report.pdf
 

Gulshan serialization inJava PPT ex.pptx

  • 1. By – Gulshan kushwaha
  • 2. . Serialization in Java : Java Serialization is the mechanism in which the state of an object is converted to a byte stream so that the byte stream can be reverted back into the copy of the object written into a file or stored into a database. It includes information about object’s type and types of data stored in the object. Once the object is serialized into written into a file, it can be read from the file and deserialized which means that the type of information and bytes that represent the object can be utilized to create object in the memory
  • 3. Copyright @ 2015 Learntek. All Rights Reserved. 3 Let’s understand streams in computer systems before proceeding further. A stream is simply a sequence of data elements. Data in the form of streams is generated from a source and consumed at a destination. Different data streams in the computer systems are: 1. Byte Stream – It is a low level I/O operation and does not have any encoding scheme. The Java program should have a buffered approach for I/O operations to process Byte Stream.
  • 4. Copyright @ 2015 Learntek. All Rights Reserved. 4 2. Data Stream – Data Stream allows to read-write primitive data types and used to perform binary I/O operations on primitive data types. I/O operations can be performed for byte, char, boolean, short, int, long, float, double and strings efficiently and conveniently. 3. Character Stream – The character stream can easily translate to and from local character set unlike byte stream. It has a proper encoding scheme such as UNICODE, ASCII and is composed of streams of characters. In Java UNICODE system is followed to store characters as character stream.
  • 5. Copyright @ 2015 Learntek. All Rights Reserved. 5 4. Object Stream – Object stream can covert the state of an object into a byte stream so that it can be stored into a database, file or transported to any location (Serialization) and used at a later point of time for retrieving the stored values and restoring the old state of the object. The process of serialization is instance independent which means an object can be serialized on one platform and deserialized on an entirely different platform. To make an object serializable we use java.io.Serializable interface.
  • 6. Copyright @ 2015 Learntek. All Rights Reserved. 6 Both the classes Object Input Stream and Object Output Stream are high-level streams and extend java.io.InputStream and java.io.OutputStream. The ObjectOutputStream has many write methods for writing different data types. One of the popular write method in ObjectOutputStream is: This method serializes an object and converts it into stream of bytes and sends it to output stream. The popular method to read an object in ObjectInputStream is:
  • 7. Copyright @ 2015 Learntek. All Rights Reserved. 7 This method reads the stream of bytes and converts it back to an object which is called deserialization. Java Serialization API contains methods for serialization and deserialization. A class must implement java.io.Serializable interface to serialize an object. Let’s understand the concept of Serialization with the help of an example.
  • 8. Copyright @ 2015 Learntek. All Rights Reserved. 8 package com.serialization;import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream;public class SerializationDemoExample { /** * The method will read data from file for deSerialization. * @param file * @return * @throws IOException * @throws ClassNotFoundException */public static Object deSerialize(String file) throws IOException, ClassNotFoundException { FileInputStream fileInputStream = new FileInputStream(file); BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); ObjectInputStream objectInputStream = new ObjectInputStream(bufferedInputStream); Object object = objectInputStream.readObject(); objectInputStream.close(); return object; }/** * The method writes data to file for Serialization. * @param file * @param object * @throws IOException */public static void serialize(String file, Object object) throws IOException { FileOutputStream fileOutputStream = new FileOutputStream(file); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); ObjectOutputStream objectOutputStream = new ObjectOutputStream(bufferedOutputStream); objectOutputStream.writeObject(object); objectOutputStream.close(); } }
  • 9. Copyright @ 2015 Learntek. All Rights Reserved. 9 This class defines two methods – deserialize and serialize. In the deSerialize method the path and file name of the file is called. This file contains the byte stream of object’s state. Once the file name and path are called the deSerialize method returns the object that can be down casted to the corresponding serialized class object. During deSerialize method we open the file in read mode using FileInputStream class and pass the object to BufferedInputStream class constructor. The object is then passed to the constructor class ObjectInputStream while instantiating. In ObjectInputStream class we call the readObject() method which will carry out the actual deserialization.
  • 10. Copyright @ 2015 Learntek. All Rights Reserved. 10 In the serialize method there are two parameters i.e., file path & name and data object which is required to be serialized. In this method we first open the file in write mode using FileOutputStream class and pass the object to BufferedOutputStream class constructor. Then the object is passed to ObjectOutputStream class while instantiating and writeObject() method is called to serialize the data object and write byte stream into opened file.
  • 11. Copyright @ 2015 Learntek. All Rights Reserved. 11 There are certain fields in the class of an object which you may not want to serialize such as sensitive information (keys, password, etc.). We protect those fields from getting saved during the process of serialization. Using the keyword transient before any field of an object won’t get serialized since transient objects are not eligible for serialization. When deserialized the value of these transient fields will have the default value.
  • 12. Copyright @ 2015 Learntek. All Rights Reserved. 12 package com.serialization; import java.io.IOException; public class SerializationImplDemo { public static void main(String args[]) { DataObject dataObject = new DataObject(); dataObject.setClient(“Yolanda”); dataObject.setStore(“Programming store”); dataObject.setId(“hhhhh”); dataObject.setPasswordKeys(“$MyG0tt!!”); try { SerializationDemoExample.serialize(“file.txt”, dataObject); DataObject object = (DataObject) SerializationDemoExample.deSerialize(“file.txt”); System.out.println(object.toString()); } catch (IOException exp) { exp.printStackTrace(); } catch (ClassNotFoundException exp) { exp.printStackTrace(); } } }
  • 13. Copyright @ 2015 Learntek. All Rights Reserved. 13 package com.serialization; import java.io.Serializable; public class DataObject implements Serializable{ private static final long serialVersionUID = 1L; private String client; private String store; transient private String id; transient private String passwordKeys; public String getClient() { return client; } public void setClient(String client) { this.client = client; } public String getStore() { return store; } public void setStore(String store) { this.store = store; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPasswordKeys() { return passwordKeys; } public void setPasswordKeys(String passwordKeys) { this.passwordKeys = passwordKeys; } @Override public String toString() { String result = “client : ” + client + “nstore : ” + store + “nID : ” + id + “npasswordKeys : ” + passwordKeys; return result; } } Serialization in Java Example 3 : DataObject.java
  • 14. Copyright @ 2018 Learntek. All Rights Reserved. 14 Thank you