-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStudentStore.java
More file actions
80 lines (72 loc) · 2.73 KB
/
StudentStore.java
File metadata and controls
80 lines (72 loc) · 2.73 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
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
public class StudentStore {
private final Path csvPath;
public StudentStore(String path) {
this.csvPath = Paths.get(path);
ensureFileExists();
}
private void ensureFileExists() {
try {
Path parent = csvPath.getParent();
if (parent != null && !Files.exists(parent)) {
Files.createDirectories(parent);
}
if (!Files.exists(csvPath)) {
try (BufferedWriter bw = Files.newBufferedWriter(csvPath, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
bw.write("id,name,age,email,program,gpa");
bw.newLine();
}
}
} catch (IOException e) {
throw new RuntimeException("Failed to initialize storage file: " + e.getMessage());
}
}
public List<Student> loadAll() {
List<Student> students = new ArrayList<Student>();
try (BufferedReader br = Files.newBufferedReader(csvPath, StandardCharsets.UTF_8)) {
String line;
boolean first = true;
while ((line = br.readLine()) != null) {
if (first) { first = false; continue; } // header
if (line.trim().isEmpty()) continue;
students.add(Student.fromCsvRow(line));
}
} catch (IOException e) {
throw new RuntimeException("Failed to read CSV: " + e.getMessage());
}
return students;
}
public void saveAll(List<Student> students) {
try (BufferedWriter bw = Files.newBufferedWriter(csvPath, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
bw.write("id,name,age,email,program,gpa");
bw.newLine();
for (Student s : students) {
bw.write(s.toCsvRow());
bw.newLine();
}
} catch (IOException e) {
throw new RuntimeException("Failed to write CSV: " + e.getMessage());
}
}
public int nextId(List<Student> students) {
int max = 0;
for (Student s : students) {
if (s.getId() > max) max = s.getId();
}
return max + 1;
}
public int findIndexById(List<Student> students, int id) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getId() == id) return i;
}
return -1;
}
}