-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTaskStorage.java
More file actions
64 lines (55 loc) · 1.84 KB
/
Copy pathTaskStorage.java
File metadata and controls
64 lines (55 loc) · 1.84 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
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class TaskStorage {
private static final String FILE_NAME = "tasks.json";
// create file if it doesn't exist
public static void createFile() {
File file = new File(FILE_NAME);
if (!file.exists()) {
try (FileWriter fw = new FileWriter(file)) {
fw.write("[]"); // empty list
} catch (IOException e) {
System.out.println("Error for creating the file " + e.getMessage());
}
}
}
// load tasks from file
public static List<Task> loadTasks() {
List<Task> tasks = new ArrayList<>();
try {
String content = Files.readString(Path.of(FILE_NAME)).trim();
if (!content.startsWith("[") || !content.endsWith("]")) return tasks;
content = content.substring(1, content.length() - 1).trim(); // eliminate [ and ]
if (content.isEmpty()) return tasks;
String[] jsonTasks = content.split("},\\s*\\{");
for (int i = 0; i < jsonTasks.length; i++) {
String json = jsonTasks[i];
if (!json.startsWith("{")) json = "{" + json;
if (!json.endsWith("}")) json = json + "}";
tasks.add(Task.fromJSON(json));
}
} catch (IOException e) {
System.out.println("Error at reading the file: " + e.getMessage());
}
return tasks;
}
// save tasks in file
public static void saveTasks(List<Task> tasks) {
try (FileWriter writer = new FileWriter(FILE_NAME)) {
writer.write("[\n");
for (int i = 0; i < tasks.size(); i++) {
writer.write(" " + tasks.get(i).toJSON());
if (i != tasks.size() - 1) writer.write(",");
writer.write("\n");
}
writer.write("]");
} catch (IOException e) {
System.out.println("Error at saving the file: " + e.getMessage());
}
}
}