-
Notifications
You must be signed in to change notification settings - Fork 0
/
Test.java
96 lines (78 loc) · 2.55 KB
/
Test.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package stc.utils;
import java.io.*;
/**
* @author : hoangtq
* @since : 13:48 15/09/2020, Tue
**/
public class Test {
public static void main(String[] args) {
Test main = new Test();
UserProfile writeUser = new UserProfile(1001, "hoangtq", "Tran Quang Hoang");
System.out.println("Before write: ");
System.out.println(writeUser.toString());
String pathToFile = "logs/log.txt";
main.writeObjectToFile(pathToFile, writeUser);
UserProfile readUser = (UserProfile) main.readObjectToFile(pathToFile);
System.out.println("After write: ");
System.out.println(readUser.toString());
}
public void writeObjectToFile(String pathToFile, Object object) {
try (FileOutputStream fileOut = new FileOutputStream(pathToFile);
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
) {
objectOut.writeObject(object);
objectOut.close();
System.out.println("Write done!");
} catch (Exception ex) {
ex.printStackTrace();
}
}
public Object readObjectToFile(String pathToFile) {
Object obj = null;
try (FileInputStream fis = new FileInputStream(pathToFile);
ObjectInputStream ois = new ObjectInputStream(fis);
) {
obj = ois.readObject();
System.out.println("Read done!");
} catch (Exception ex) {
ex.printStackTrace();
}
return obj;
}
static class UserProfile implements Serializable {
private int id;
private String userName;
private String fullName;
public UserProfile(int id, String userName, String fullName) {
this.id = id;
this.userName = userName;
this.fullName = fullName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
@Override
public String toString() {
return "UserProfile{" +
"id=" + id +
", userName='" + userName + '\'' +
", fullName='" + fullName + '\'' +
'}';
}
}
}