ObjectOutputStream
class.
ObjectInputStream
class.
import java.io.Serializable;
public class Student implements Serializable
{
// Define the instance variables
private String name;
private int rollno;
// Constructor to initialize the variables
public Student(String name, int rollno)
{
this.name = name;
this.rollno = rollno;
}
// Getters for the variables
public String getName() {
return name;
}
public int getRollno() {
return rollno;
}
// Displaying student details
public void display()
{
System.out.println("Name: " + name);
System.out.println("Roll No: " + rollno);
}
}
ObjectOutputStream
class as follows:
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
public class SerializationExample
{
public static void main(String[] args)
{
// Create a Student object
Student student = new Student("Deepak", 101);
// Serialize the object
try (
FileOutputStream fileOut = new FileOutputStream("student.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut)
)
{
out.writeObject(student); // Serialize the student object
System.out.println("Student object has been serialized.");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Student object has been serialized.
ObjectInputStream
class as follows:
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
public class DeserializationExample
{
public static void main(String[] args)
{
// Deserialize the object
try (
FileInputStream fileIn = new FileInputStream("student.ser");
ObjectInputStream in = new ObjectInputStream(fileIn)
)
{
Student student = (Student) in.readObject(); // Deserialize the object
System.out.println("Student object has been deserialized.");
student.display(); // Display the student details
}
catch (IOException | ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
Student object has been deserialized. Name: Deepak Roll No: 101
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.