-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileDataModel.java
More file actions
102 lines (80 loc) · 2.58 KB
/
FileDataModel.java
File metadata and controls
102 lines (80 loc) · 2.58 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package data;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import model.*;
import jsonlib.types.JSONObject;
import jsonlib.types.JSONList;
import jsonlib.types.JSONDict;
import jsonlib.JSONSerializableFactory;
import jsonlib.JSONParser;
import jsonlib.JSONExpectFailedException;
public class FileDataModel {
private static final String BOOKS_FILEPATH = "books.json";
private static final String STUDENTS_FILEPATH = "students.json";
private static final String CATEGORIES_FILEPATH = "categories.json";
private static final String LOANS_FILEPATH = "loans.json";
public List<Book> loadBooks() {
return loadFromFile(BOOKS_FILEPATH);
}
public List<Student> loadStudents() {
return loadFromFile(STUDENTS_FILEPATH);
}
public List<Category> loadCategories() {
return loadFromFile(CATEGORIES_FILEPATH);
}
public List<Loan> loadLoans() {
return loadFromFile(LOANS_FILEPATH);
}
public void saveBooks(List<Book> books) {
writeToFile(BOOKS_FILEPATH, JSONObject.fromList(books).toString());
}
public void saveStudents(List<Student> students) {
writeToFile(STUDENTS_FILEPATH, JSONObject.fromList(students).toString());
}
public void saveCategories(List<Category> categories) {
writeToFile(CATEGORIES_FILEPATH, JSONObject.fromList(categories).toString());
}
public void saveLoans(List<Loan> loans) {
writeToFile(LOANS_FILEPATH, JSONObject.fromList(loans).toString());
}
public void writeToFile(String filePath, String data) {
try (FileWriter writer = new FileWriter(filePath)) {
writer.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
public String readFromFile(String filePath) {
String content = new String();
try {
content = String.join("\n", Files.readAllLines(Paths.get(filePath)));
} catch (IOException e) {
return null;
}
return content;
}
public <T> List<T> loadFromFile(String filePath) {
String content = readFromFile(filePath);
if (content == null) {
return new ArrayList<>();
}
JSONParser parser = new JSONParser(content);
JSONObject jsonObj = null;
try {
jsonObj = parser.parse();
} catch (JSONExpectFailedException e) {
e.printStackTrace();
}
List<T> result = new ArrayList<>();
JSONList listJSON = (JSONList) jsonObj;
for (JSONObject itemJSON : listJSON) {
T item = (T) JSONSerializableFactory.deserialize((JSONDict) itemJSON);
result.add(item);
}
return result;
}
}