In a software project, in many instances, there are necessities to transfer the data, and it can be handled by using ObjectOutputStream and ObjectInputStream from Java IO packages. Usually, the data is written in binary format and hence we cannot view the contents. Serialization is the process of writing an object to an output stream. We can write a class object itself, which contains a combination of primitive datatype and graphs of Java objects. Deserialization is the process of reconstructing an object from an input stream.
Implementation: Let us see the ObjectOutputStream with an is illustrated for which we create a POJO class called “VehicleSpecifications”.
Note: It should implement Serializable, otherwise, java.io.NotSerializableException will be thrown.
Example 1:
Tóm Tắt
Java
import
java.io.Serializable;
public
class
VehicleSpecifications
implements
Serializable {
private
String color;
private
String type;
private
String name;
private
double
price;
public
VehicleSpecifications() {}
public
VehicleSpecifications(String color, String type,
String name,
double
price)
{
this
.color = color;
this
.type = type;
this
.name = name;
this
.price = price;
}
public
double
getPrice() {
return
price; }
public
void
setPrice(
double
price)
{
this
.price = price;
}
public
String getName() {
return
name; }
public
void
setName(String name) {
this
.name = name; }
public
String getColor() {
return
color; }
public
void
setColor(
final
String color)
{
this
.color = color;
}
public
String getType() {
return
type; }
public
void
setType(
final
String type)
{
this
.type = type;
}
}
No output is as till now by far we have implemented just the constructors and defined body of methods including getters and setters.
Now let us create a few vehicle specifications and write them in a file. As VehicleSpecifications implemented Serializable functionality, the data can be written to a file in a binary format. For this we will be using “writeObject” function and by using that we can write class attributes using write methods provided by ObjectOutputStream.
Example 2:
Java
import
java.io.FileOutputStream;
import
java.io.IOException;
import
java.io.ObjectOutputStream;
import
java.util.ArrayList;
import
java.util.List;
public
class
VehicleSpecificationsSerializer {
public
static
void
main(String[] args)
{
String sampleOutputFile =
"VehicleSpecifcation.db"
;
try
{
ObjectOutputStream vehicleObjectOutput
=
new
ObjectOutputStream(
new
FileOutputStream(sampleOutputFile));
List<VehicleSpecifications> listSpecifications
=
new
ArrayList<VehicleSpecifications>();
listSpecifications.add(
new
VehicleSpecifications(
"Radiant Red"
,
"SUV"
,
"WR-V"
,
1700000f));
listSpecifications.add(
new
VehicleSpecifications(
"Metallic Blue"
,
"SUV"
,
"WR-V"
,
1800000f));
listSpecifications.add(
new
VehicleSpecifications(
"Black"
,
"SUV"
,
"WR-V"
, 1900000f));
vehicleObjectOutput.writeObject(
listSpecifications);
vehicleObjectOutput.close();
}
catch
(IOException ex) {
ex.printStackTrace();
}
}
}
Note: On execution of the above code, we can see that the data is written in a binary format that means, it is a non-readable format only.
So In order to get the data in a readable format, we are using ObjectInputStream and as we have to retrieve the class object data(i.e. VehicleSpecifications data), we need to use readObject() method, which can read class attributes using read() methods provided by ObjectInputStream.
Example 3:
Java
import
java.io.FileInputStream;
import
java.io.IOException;
import
java.io.ObjectInputStream;
import
java.util.ArrayList;
import
java.util.List;
public
class
VehicleSpecificationsDeSerializer {
public
static
void
main(String[] args)
{
String sampleInputFile =
"VehicleSpecifcation.db"
;
try
{
ObjectInputStream vehicleObjectInputStream
=
new
ObjectInputStream(
new
FileInputStream(sampleInputFile));
List<VehicleSpecifications>
vehicleSpecificationsListData
=
new
ArrayList<VehicleSpecifications>();
vehicleSpecificationsListData
= (ArrayList<VehicleSpecifications>)
vehicleObjectInputStream.readObject();
for
(
int
i =
0
;
i < vehicleSpecificationsListData.size();
i++) {
VehicleSpecifications vehicleSpecifications
= vehicleSpecificationsListData.get(i);
System.out.println(
"Color .."
+ vehicleSpecifications.getColor());
System.out.println(
"Name .."
+ vehicleSpecifications.getName());
System.out.println(
"Price .."
+ vehicleSpecifications.getPrice());
System.out.println(
"Type .."
+ vehicleSpecifications.getType());
}
vehicleObjectInputStream.close();
}
catch
(IOException ex) {
ex.printStackTrace();
}
catch
(ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Output:
Output explanation:
So, we are seeing the output in a human-readable format. So our entire set of class objects can be portable using ObjectInput and ObjectOutput streams provided by java.io packages. Hence, now let us finally discuss out the differences between ObjectOutputStream and ObjectInputStream after having an internal workflow understanding of them. They are illustrated below in a tabular format shown as below:
ObjectOutputStreamObjectInputStreamWrites Java objects Reads Java objectsUsing ArrayList, we can write multiple Java objectsVia ArrayList, we can read and retrieve multiple Java objectsBy default, ArrayList is serializable, and hence no need to implement serializable if we are writing ArrayList of objects like String, but the elements should be serializable. writeObject() is used to write ArrayList of dataDuring deserialization of ArrayList object, readObject() is used to read the ArrayList of dataIf we are using a class object(like the example as we discussed above), the class should implement serializable and then only while using writeObject() method, java.io.NotSerializableException will not be thrownWe need to cast the same format of object while using readObject()writeObject() method writes the serialized data in binary formatreadObject() method deserializes and reads the dataThe binary format is not readable. Though we are passing primitive data like String, double, etc., while writing, the data is getting stored in binary format.In order to get the data in perfect class format, we need to use ObjectInputStream which deserializes data and we can get all primitive data that is writtenAs a whole object, it is getting written, there is no loss of data provided the object is serialized and written in a proper formatSimilarly, whole object is read, there is no loss of data, and we can easily iterate the data also.
Not only writing class objects by means writeObject(), it also supports other write methods like as depicted below and many more methods to write for each and every data type.
write(byte[] buffer)-> Writes an array of bytes.
writeBoolean(boolean value) -> Write boolean value
writeDouble(double value)-> Write 64 bit double value
writeInt(int value)-> Writes 32 bit int
Not only reading class objects by means readObject(), it also supports other read methods like depicted as below and many more methods to read each and every datatype.
read()-> Reads byte of data
readBoolean() -> To read a boolean.
readDouble()-> To read a 64 bit double.
readInt()->To Read a 32 bit int.
Possible exceptions for ObjectOutputStream is as follows:
IOException – in case of any I/O error occurs during writing stream header
SecurityException
NullPointerException – if OutputStream not initialized and hence it may be null
Possible exceptions for ObjectInputStream is as follows:
StreamCorruptedException – Incorrect stream header
IOException – In case of any I/O error occurs while reading stream header
SecurityException
NullPointerException – if Inputstream not initialized and hence it may be null
Possible exceptions for writeObject is as follows:
InvalidClassException – Serialization of class should be correct and if something is wrong.
NotSerializableException – Some object to be serialized does not implement the java.io.Serializable interface. This will commonly occur and hence it is mandatory to make the class to implement Serializable
IOException – During writing, if IO error occur by the underlying OutputStream.
Possible exceptions for readObject is as follows:
InvalidClassException – Serialization of class should be correct and if something is wrong.
ClassNotFoundException – Class of a serialized object should be available and if cannot be found.
IOException – During reading, if IO error occur by the underlying InputStream
StreamCorruptedException
OptionalDataException
My Personal Notes
arrow_drop_up