-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathSerializeObject.java
More file actions
58 lines (50 loc) · 1.68 KB
/
Copy pathSerializeObject.java
File metadata and controls
58 lines (50 loc) · 1.68 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
//Save Object in a file
public class SerializeObject {
public static void main(String[] args) throws Exception {
ObjectOutputStream output = null;
UserProfile localprofile = new UserProfile(
"Jaime", "jaimito@gmail.com", "Green", "Some other data"
);
//Serializable
try {
output = new ObjectOutputStream( new FileOutputStream( "userProfile.txt" ) );
output.writeObject(localprofile);
} finally {
if (output != null){
output.close();
}
}
//Deserialize
UserProfile restoredprofile;
ObjectInputStream input = null;
try {
input = new ObjectInputStream( new FileInputStream( "userProfile.txt" ) );
restoredprofile = (UserProfile) input.readObject();
System.out.println(restoredprofile);
} finally {
if (input != null){
input.close();
}
}
}
}
class UserProfile implements java.io.Serializable {
private String name, email, themecolor;
private transient String something;
public UserProfile(String name, String email, String themecolor, String something){
this.name = name;
this.email = email;
this.themecolor = themecolor;
this.something = something;
}
public String toString(){
return "User: " + name +
"\nEmail: " + email +
"\nTheme Color: " + themecolor +
"\nSomething (transient): " + something;
}
}