-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSerializePerson.java
More file actions
39 lines (33 loc) · 1.2 KB
/
Copy pathSerializePerson.java
File metadata and controls
39 lines (33 loc) · 1.2 KB
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
34
35
36
37
38
39
import java.io.*;
class Person implements Serializable {
private static final long serialVersionUID = 1L;
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class SerializePerson {
public static void main(String[] args) {
Person p1 = new Person("Nitanshu Tak", 20);
// Serialization
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.txt"))) {
out.writeObject(p1);
System.out.println("Person object serialized.");
} catch (IOException e) {
System.out.println("Error serializing object.");
}
// Deserialization
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.txt"))) {
Person p2 = (Person) in.readObject();
System.out.println("Deserialized Person:");
p2.display();
} catch (IOException | ClassNotFoundException e) {
System.out.println("Error deserializing object.");
}
}
}