文章目录

序列化工具类,用于序列化对象对文件或从文件反序列化对象

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
public class Serialization(String filePath) {
public static Object deserialization(String filePath){
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(filePath));
Object o = in.readOject();
in.close();
return o;
} catch (FileNotFoundException e) {
throw new RuntimeException("FileNotFoundException occurred. ", e);
} catch (ClassNotFoundException e) {
throw new RuntimeException("ClassNotFoundException occurred. ", e);
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
}
}
}
}

public static void serialization(String filePath,Object obj) {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new fileOutputStream(filePath));
out.writeObject(obj);
out.close();
} catch (FileNotFoundException e) {
throw new RuntimeException("FileNotFoundException occurred. ", e);
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
}
}
}
}
}

文章目录