-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSavingsService.java
More file actions
57 lines (51 loc) · 1.62 KB
/
SavingsService.java
File metadata and controls
57 lines (51 loc) · 1.62 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.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class SavingsService
{
private static final String fileName = "savings_goals.txt";
public static void saveGoal(SavingsGoal goal)
{
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true)))
{
writer.write(goal.getGoalName() + "|" + goal.getTargetAmount());
writer.newLine();
}
catch (IOException e)
{
System.err.println("Error saving goals: " + e.getMessage());
}
}
public static List<SavingsGoal> getAllGoals()
{
List<SavingsGoal> goals = new ArrayList<>();
File file = new File(fileName);
if (!file.exists())
{
return goals;
}
try (BufferedReader reader = new BufferedReader(new FileReader(file)))
{
String line;
while ((line = reader.readLine()) != null)
{
String[] parts = line.split("\\|");
if (parts.length == 2)
{
SavingsGoal goal = new SavingsGoal(parts[0], Double.parseDouble(parts[1]));
goals.add(goal);
}
}
}
catch (IOException e)
{
System.err.println("Error loading goals: " + e.getMessage());
}
return goals;
}
}