-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileHandler.java
More file actions
42 lines (37 loc) · 1.58 KB
/
FileHandler.java
File metadata and controls
42 lines (37 loc) · 1.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
import java.io.*;
import java.util.*;
public class FileHandler {
private static final String FILE_NAME = "students.txt";
public static void saveToFile(List<Student> students) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_NAME))) {
for (Student s : students) {
writer.write(s.getId() + "," + s.getName() + "," + s.getAge() + "," + s.getCourse() + "," + s.getMarks());
writer.newLine();
}
} catch (IOException e) {
System.out.println("Error saving data: " + e.getMessage());
}
}
public static List<Student> loadFromFile() {
List<Student> students = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME))) {
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
if (parts.length == 5) {
String id = parts[0].trim();
String name = parts[1].trim();
int age = Integer.parseInt(parts[2].trim());
String course = parts[3].trim();
double marks = Double.parseDouble(parts[4].trim());
students.add(new Student(id, name, age, course, marks));
}
}
} catch (FileNotFoundException e) {
// File doesn't exist yet; no students to load
} catch (IOException e) {
System.out.println("Error loading data: " + e.getMessage());
}
return students;
}
}