-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCsvHandler.java
More file actions
81 lines (67 loc) · 2.5 KB
/
CsvHandler.java
File metadata and controls
81 lines (67 loc) · 2.5 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
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
public class CsvHandler {
private final String filename;
public CsvHandler(String filename) {
this.filename = filename;
}
public List<Task> loadTasks() {
List<Task> tasks = new ArrayList<>();
File file = new File(filename);
if (!file.exists()) {
return tasks; // No saved tasks yet
}
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
if (line.trim().isEmpty()) continue;
Task task = parseLine(line);
if (task != null) {
tasks.add(task);
}
}
System.out.println("Loaded " + tasks.size() + " task(s) from " + filename);
return tasks;
}
public void saveTasks(List<Task> tasks) {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
for (Task task : tasks) {
writer.write(formatTask(task));
writer.newLine();
}
}
private Task parseLine(String line) {
line = line.trim();
if (line.isEmpty()) return null;
if (line.startsWith("\"")) {
int endQuote = line.indexOf("\"", 1);
if (endQuote == -1) return null;
String description = line.substring(1, endQuote);
String rest = line.substring(endQuote + 1).trim();
if (!rest.startsWith(",")) return null;
String boolStr = rest.substring(1).trim();
boolean completed = Boolean.parseBoolean(boolStr);
return new Task(description, completed);
} else {
int comma = line.indexOf(",");
if (comma == -1) return null;
String description = line.substring(0, comma).trim();
String boolStr = line.substring(comma + 1).trim();
boolean completed = Boolean.parseBoolean(boolStr);
return new Task(description, completed);
}
}
private String formatTask(Task task) {
String description = task.getDescription();
if (description.contains(",") || description.contains("\"")) {
description = description.replace("\"", "\"\"");
description = "\"" + description + "\"";
}
return description + "," + task.isCompleted();
}
}