-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLocalStorage.java
More file actions
87 lines (77 loc) · 2.29 KB
/
Copy pathLocalStorage.java
File metadata and controls
87 lines (77 loc) · 2.29 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
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
package serialize;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashSet;
/**
* @ClassName: LocalStorage
* @Description:
* @author lisi
* @date 2016Äê11ÔÂ15ÈÕ ÏÂÎç12:06:12
*
*/
public class LocalStorage {
private String parentPath = new File("").getAbsolutePath() + File.separator;
private HashSet<String> paths = new HashSet<>();
public String getParentPath() {
return parentPath;
}
public void setParentPath(String parentPath) {
this.parentPath = parentPath;
if (!this.parentPath.endsWith(File.separator))
this.parentPath += File.separator;
}
public boolean save(Serializable target, String fileName) {
boolean isSaved = false;
if (!paths.contains(fileName)) {
paths.add(fileName);
ObjectOutputStream out;
try {
out = new ObjectOutputStream(new FileOutputStream(getAbsPath(fileName)));
out.writeObject(target);
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return isSaved;
}
private String getAbsPath(String fileName) {
return parentPath + fileName;
}
public Serializable load(String fileName) {
Serializable target = null;
if (paths.contains(fileName)) {
ObjectInputStream in;
try {
in = new ObjectInputStream(new FileInputStream(getAbsPath(fileName)));
target = (Serializable) in.readObject();
in.close();
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return target;
}
public static void main(String[] args) {
System.out.println(new LocalStorage().parentPath);
Employee ming = new Employee("jim", 13, 5);
Employee gao = new Employee("tom", 15, 3);
LocalStorage storage = new LocalStorage();
storage.setParentPath("F:\\test");
System.out.println(storage.getParentPath());
storage.save(ming, "ming.dat");
storage.save(gao, "gao.dat");
Serializable obj = storage.load("ming.dat");
if (obj instanceof Employee) {
Employee ming1 = (Employee) storage.load("ming.dat");
System.out.println(ming1);
}
}
}