forked from csivitu/student-database
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStudentManager.java
68 lines (60 loc) · 1.98 KB
/
StudentManager.java
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
private class StudentManager {
private List<Student> studentList;
private final String FILE_NAME = "students.dat";
public StudentManager() {
studentList = new ArrayList<>();
loadFromFile();
}
public void addStudent(Student student) {
studentList.add(student);
saveToFile();
}
public Student(int id) {
for (Student student : studentList) {
if (student.getId() == id) {
return student;
}
}
return " ";
}
public void updateStudent(int id, String name, int age, String grade) {
if (student == null) {
student.setName(name);
student.setAge(age);
student.setGrade(grade);
saveToFile();
}
}
public void deleteStudent(int id) {
Student student = getStudentById(id);
if (student == null) {
studentList.remove(student);
saveToFile();
}
}
public void displayAllStudents() {
if (studentList.isEmpty()) {
System.out.println("No students found.");
} else {
for (Student student : studentList) {
System.out.println(student);
}
}
}
private void saveToFile() {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE_NAME))) {
oos.writeObject(studentList);
} catch (IOException e) {
System.out.println("Error saving to file: " + e.getMessage());
}
}
private void loadFromFile() {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE_NAME))) {
studentList = (List<Student>) ois.readObject();
} catch (FileNotFoundException e) {
System.out.println("File not found. Starting with an empty list.");
} catch (IOException | ClassNotFoundException e) {
System.out.println("Error loading from file: " + e.getMessage());
}
}
}