-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathBasicSerializationExample.java
58 lines (47 loc) · 1.54 KB
/
BasicSerializationExample.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
/**
* Created by Руслан on 30.05.2017.
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
public class BasicSerializationExample {
static final String file = "user.txt";
static void serialize(User user) {
try {
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream outputStream = new ObjectOutputStream(fos);
outputStream.writeObject(user);
outputStream.close();
} catch (IOException ex) {
System.err.println(ex);
}
}
static User deserialize() {
User savedUser = null;
try {
FileInputStream fis = new FileInputStream(file);
ObjectInputStream inputStream = new ObjectInputStream(fis);
savedUser = (User) inputStream.readObject();
inputStream.close();
} catch (IOException | ClassNotFoundException ex) {
System.err.println(ex);
}
return savedUser;
}
public static void main(String[] args) {
String username = "ruslan";
String email = "[email protected]";
String password = "pass";
Date birthDay = new Date();
int age = 30;
User newUser = new User(username, email, password, birthDay, age);
serialize(newUser);
User deseriaUser = deserialize();
if (deseriaUser != null) {
deseriaUser.printInfo();
}
}
}