forked from Pooja0504/testDemo
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathExternExample.java
75 lines (66 loc) · 1.72 KB
/
ExternExample.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.io.*;
class Car implements Externalizable {
static int age;
String name;
int year;
Car(String n, int y)
{
this.name = n;
this.year = y;
age = 10;
}
@Override
public void writeExternal(ObjectOutput out)
throws IOException
{
out.writeObject(name);
out.writeInt(age);
out.writeInt(year);
}
@Override
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
name = (String)in.readObject();
year = in.readInt();
age = in.readInt();
}
@Override public String toString()
{
return ("Name: " + name + "\n"
+ "Year: " + year + "\n"
+ "Age: " + age);
}
}
public class ExternExample {
public static void main(String[] args)
{
Car car = new Car("Shubham", 1995);
Car newcar = null;
// Serialize the car
try {
FileOutputStream fo
= new FileOutputStream("gfg.txt");
ObjectOutputStream so
= new ObjectOutputStream(fo);
so.writeObject(car);
so.flush();
}
catch (Exception e) {
System.out.println(e);
}
// Deserializa the car
try {
FileInputStream fi
= new FileInputStream("gfg.txt");
ObjectInputStream si
= new ObjectInputStream(fi);
newcar = (Car)si.readObject();
}
catch (Exception e) {
System.out.println(e);
}
System.out.println("The original car is:\n" + car);
System.out.println("The new car is:\n" + newcar);
}
}