-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathPlayerDataController.java
More file actions
45 lines (29 loc) · 1.15 KB
/
PlayerDataController.java
File metadata and controls
45 lines (29 loc) · 1.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
package co.ppg2.controllers;
import co.ppg2.model.Player;
import java.io.*;
import java.util.ArrayList;
public class PlayerDataController {
private static final String FILE_NAME = "players.dat";
public static void savePlayers(ArrayList<Player> players) {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE_NAME))) {
oos.writeObject(players);
} catch (IOException e) {
e.printStackTrace();
}
}
public static ArrayList<Player> loadPlayers() {
ArrayList<Player> players = new ArrayList<>();
File file = new File(FILE_NAME);
//TODO: consider adding conditional to check if file exists
if (file.exists()) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE_NAME))) {
players = (ArrayList<Player>) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
} else {
System.out.println("Player file does not exist. Starting with an empty player list.");
}
return players;
}
}