-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathScore.java
94 lines (59 loc) · 1.81 KB
/
Score.java
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
83
84
85
86
87
88
89
90
91
92
93
94
import java.io.*;
//Class for files.
/**
* Class to save and retrieve top scores.
*/
public class Score {
/**
* Method to update high score.
*/
public void updateScores(int score) {
//Holds high score.
int fileScore = readScore();
//Calculate highscore.
if (score > fileScore) {
fileScore = score;
}
//Write binary data to file.
try {
FileOutputStream fstream = new FileOutputStream("Score.dat");
DataOutputStream outputFile = new DataOutputStream(fstream);
outputFile.writeInt(fileScore);
outputFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Method that returns the high score.
*/
public int readScore() {
//Holds high score.
int fileScore = 0;
//Flag to stop reading file.
boolean endOfFile = false;
//Read binary data, or create if not there.
try {
FileInputStream fstream = new FileInputStream("Score.dat");
DataInputStream inputFile = new DataInputStream(fstream);
while (!endOfFile) {
try {
fileScore = inputFile.readInt();
} catch (EOFException e) {
endOfFile = true;
}
}
inputFile.close();
} catch (IOException e) {
try {
FileOutputStream fstream = new FileOutputStream("Score.dat");
DataOutputStream outputFile = new DataOutputStream(fstream);
outputFile.writeInt(0);
outputFile.close();
} catch (IOException ex) {
e.printStackTrace();
}
}
return fileScore;
}
}