📘 Lesson · Lesson 46
Serialization
Serialization
What is Serialization?
Serialization converts an object into bytes so it can be saved to a file or sent over a network. Deserialization rebuilds the object from those bytes.
Making a Class Serializable
import java.io.*;
class Student implements Serializable {
int id; String name;
Student(int id, String name) { this.id=id; this.name=name; }
}
// Serialize
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("s.ser"));
out.writeObject(new Student(1, "Aman"));
out.close();
Summary
- Implement
Serializable; use ObjectOutputStream to save, ObjectInputStream to read. - Serialization = object→bytes; deserialization = bytes→object.
Serialization क्या है?
Serialization object को bytes में बदलता है ताकि उसे file में save या network पर भेजा जा सके। Deserialization उन bytes से object फिर बनाता है।
Class को Serializable बनाना
import java.io.*;
class Student implements Serializable {
int id; String name;
Student(int id, String name) { this.id=id; this.name=name; }
}
// Serialize
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("s.ser"));
out.writeObject(new Student(1, "Aman"));
out.close();
सारांश
Serializableimplement करें; save को ObjectOutputStream, read को ObjectInputStream।- Serialization = object→bytes; deserialization = bytes→object।