[post-views]
In this lesson, you will learn.
The following is the I/O stream classes hierarchy.

In this lesson, we will discuss about the ObjectInputStream and ObjectOutputStream classes to write object data on the file.
Serializable Interface: Objects of any class that implements the java.io.Serializable interface can be serialized. This interface acts as a marker, indicating to the JVM that the class is eligible for serialization. It doesn’t contain any methods to implement.
ObjectOutputStream and ObjectInputStream: These are high-level streams that handle the serialization and deserialization processes. ObjectOutputStream converts an object into a byte stream, while ObjectInputStream reads the byte stream to recreate the object.
Transient Keyword: If a field in a class should not be saved with the object when it is serialized, it is marked as transient. The field will be ignored during serialization and, during deserialization, the field will be initialized with a default value.
We will create a class Person that implements Serializable, and we will serialize and deserialize an instance of this class.
package serialization;
import java.io.*;
//A class that represents a person
class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
// Transient field
transient private String password;
public Person(String name, int age, String password) {
this.name = name;
this.age = age;
this.password = password;
}
public String getName() { return name; }
public int getAge() { return age; }
public String getPassword() { return password; }
@Override
public String toString() {
return "Person{name='" + name + ''' + ", age=" + age
+ ", password='" + password + ''' + '}';
}
}
//Main class to perform serialization and deserialization
public class SerializationExample {
public static void main(String[] args) {
Person person = new Person("Alice", 30, "secret123");
// Serialize the Person object
try (ObjectOutputStream out = new ObjectOutputStream
(new FileOutputStream("person.dat"))) {
System.out.println("Object: " +person);
out.writeObject(person);
System.out.println("Object has been serialized");
} catch (IOException e) {
e.printStackTrace();
}
// Deserialize the Person object
Person deserializedPerson = null;
try (ObjectInputStream in = new ObjectInputStream
(new FileInputStream("person.dat"))) {
deserializedPerson = (Person) in.readObject();
System.out.println("Object has been deserialized");
System.out.println(deserializedPerson);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Output
Object: Person{name='Alice', age=30, password='secret123'}
Object has been serialized
Object has been deserialized
Person{name='Alice', age=30, password='null'}
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.