-
Notifications
You must be signed in to change notification settings - Fork 629
/
Copy pathSerialization.java
33 lines (27 loc) · 985 Bytes
/
Serialization.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.io.*;
class Student implements Serializable {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
}
public class SerializationDemo {
public static void main(String[] args) {
try {
Student student = new Student("Alice", 20);
// Serialization
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("student.ser"));
out.writeObject(student);
out.close();
// Deserialization
ObjectInputStream in = new ObjectInputStream(new FileInputStream("student.ser"));
Student deserializedStudent = (Student) in.readObject();
in.close();
System.out.println("Deserialized Student: Name - " + deserializedStudent.name + ", Age - " + deserializedStudent.age);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}