Simplest solution is to have a serializable class to hold the high scores.
Here's one I prepared earlier:
class HighScore
implements Serializable {
private Score[] scores;
HighScore() {
this.scores = new Score[10];
}
addScore(final Score score) {
Score swap = score;
for (int s = 0;
s < 10;
s++) {
if (swap.getScore() > this.scores[s].getScore()) {
Score temp = this.scores[s];
this.scores[s] = swap;
swap = temp;
}
}
}
Score getScore(int score) {
if (score < 0 || score > 9) {
return null;
}
return this.scores[score];
}
}
class Score
implements Serializable {
private final String user;
private final int score;
Score (final String user, final int score) {
this.user = user;
this.score = score;
}
String getUser() {
return this.user;
}
int getScore() {
return this.score;
}
}
Then in the game class you can save and load it thus:
class Game {
private HighScore highScore;
void saveHighScore() {
try {
FileOutputStream fos = new FileOutputStream("highScore.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(this.highScore);
oos.flush();
} catch(IOException iex) {
iex.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch(IOException iex) {
iex.printStackTrace();
}
}
}
}
void loadHighScore () {
try {
FileInputStream fis = new FileInputStream("serial");
ObjectInputStream ois = new ObjectInputStream(fis);
this.highScore = (HighScore)ois.readObject();
} catch (IOException iex) {
iex.printStackTrace();
this.highScore = new HighScore();
} catch (ClassNotFoundException cex) {
cex.printStackTrace();
this.highScore = new HighScore();
} finally {
if (ois != null) {
try {
ois.close();
} catch(IOException iex) {
iex.printStackTrace();
}
}
}
}
}