-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileHandler.java
More file actions
57 lines (49 loc) · 2.15 KB
/
Copy pathFileHandler.java
File metadata and controls
57 lines (49 loc) · 2.15 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
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class FileHandler {
private String filename;
public FileHandler(String filename) {
this.filename = filename;
}
// Read data from file
public Map<String, String> readFromFile() {
Map<String, String> rentedLaptops = new HashMap<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
rentedLaptops.put(parts[0], parts[1]);
}
} catch (IOException e) {
e.printStackTrace();
}
return rentedLaptops;
}
// Write data to file
public void writeToFile(Map<String, String> rentedLaptops, Map<String, Laptop> availableLaptops) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
BufferedWriter returnedWriter = new BufferedWriter(new FileWriter("returnedLaptops.txt", true))) {
// Write back existing rented laptops to the file
for (Map.Entry<String, String> entry : rentedLaptops.entrySet()) {
String laptopId = entry.getKey();
String studentId = entry.getValue();
double price = availableLaptops.get(laptopId).getPrice();
writer.write(laptopId + "," + studentId + "," + price);
writer.newLine();
}
// Append returned laptops to "returnedLaptops.txt"
for (Map.Entry<String, String> entry : rentedLaptops.entrySet()) {
String laptopId = entry.getKey();
if (!availableLaptops.containsKey(laptopId)) {
String studentId = entry.getValue();
double price = availableLaptops.get(laptopId).getPrice();
returnedWriter.write(laptopId + "," + studentId + "," + price);
returnedWriter.newLine();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}