forked from yfain/Java4Kids_code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScoreManager.java
More file actions
76 lines (53 loc) · 2.15 KB
/
Copy pathScoreManager.java
File metadata and controls
76 lines (53 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package solution;
import serialization.GameState;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.util.*;
public class ScoreManager {
public static void main(String[] args) {
Path path = Paths.get("scores.ser");
List<Score> scores;
if (Files.exists(path)) {
scores = loadScores(path);
} else {
scores = new ArrayList<>();
}
Random numberGenerator = new Random();
scores.add(new Score("Mary", numberGenerator.nextInt(50000), LocalDateTime.now()));
System.out.println("All scores:");
scores.forEach(s -> System.out.println(s));
saveScores(path, scores);
System.out.println("Sorted scores (highest on top):");
Comparator<Score> byScoreDescending =
Collections.reverseOrder(Comparator.comparing(s -> s.score));
scores.stream()
.sorted(byScoreDescending)
.forEach(s -> System.out.println(s));
}
// Serialize scores into a file
private static void saveScores(Path path, List<Score> gameScores) {
try (ObjectOutputStream whereToWrite = new ObjectOutputStream(
Files.newOutputStream(path, StandardOpenOption.CREATE))){
whereToWrite.writeObject(gameScores);
} catch (IOException ioe) {
System.out.println("Can't serialize scores: " + ioe.getMessage());
}
}
// Deserialize the scores from a file
private static List<Score> loadScores(Path path){
List<Score> loadedScores= null;
try (ObjectInputStream whereToReadFrom =
new ObjectInputStream(Files.newInputStream(path))){
loadedScores= (List<Score>) whereToReadFrom.readObject();
} catch (ClassNotFoundException cnfe) {
System.out.println("Can't find the declaration of Score: " + cnfe.getMessage());
} catch (IOException ioe) {
System.out.println("Can't deserialize file: " + ioe.getMessage());
}
return loadedScores;
}
}