-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileHandler.java
More file actions
82 lines (66 loc) · 2.86 KB
/
FileHandler.java
File metadata and controls
82 lines (66 loc) · 2.86 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
82
package database;
import models.Account;
import accountTypes.*; // Import your card types
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class FileHandler {
private static final String ACCOUNTS_FILE = "approved_accounts.txt";
private static final String PENDING_FILE = "pending_accounts.txt";
// SAVE ACCOUNTS
public static void saveAccounts(List<Account> accounts, boolean isPending) {
String filename = isPending ? PENDING_FILE : ACCOUNTS_FILE;
try (BufferedWriter bw = new BufferedWriter(new FileWriter(filename))) {
for (Account a : accounts) {
bw.write(a.toCSVLine());
bw.newLine();
}
} catch (IOException e) {
System.out.println("Error saving file: " + e.getMessage());
}
}
// LOAD ACCOUNTS
public static List<Account> loadAccounts(boolean isPending) {
String filename = isPending ? PENDING_FILE : ACCOUNTS_FILE;
List<Account> list = new ArrayList<>();
File f = new File(filename);
if (!f.exists()) return list;
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = br.readLine()) != null) {
// Parsing CSV: Number|Name|Email|UniID|Pin|Type|Balance|Status
String[] parts = line.split("\\|");
if (parts.length < 8) continue; // Skip broken lines
// 1. EXTRACT DATA FROM FILE
int accNum = Integer.parseInt(parts[0]);
String name = parts[1];
String email = parts[2];
String uniId = parts[3];
// --- THIS IS THE LINE YOU WERE MISSING ---
int pin = Integer.parseInt(parts[4]);
String cardType = parts[5];
double bal = Double.parseDouble(parts[6]);
String status = parts[7];
Account a = null;
// 2. CREATE OBJECT (Now 'pin' is defined and works)
if (cardType.equals("Student")) {
a = new StudentAccount(accNum, name, email, uniId, pin);
} else if (cardType.equals("Silver")) {
a = new SilverAccount(accNum, name, email, uniId, pin);
} else if (cardType.equals("Gold")) {
a = new GoldAccount(accNum, name, email, uniId, pin);
} else if (cardType.equals("Premium")) {
a = new PremiumAccount(accNum, name, email, uniId, pin);
}
if (a != null) {
a.setBalance(bal);
a.setStatus(status);
list.add(a);
}
}
} catch (Exception e) {
System.out.println("Error loading file: " + e.getMessage());
}
return list;
}
}