//check permission first
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new HighScorePermission(gameName));
}
// need a doPrivileged block to manipulate the file
try {
AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws IOException {
Hashtable scores = null;
// try to open the existing file. Should have a locking
// protocol (could use File.createNewFile).
try {
FileInputStream fis =
new FileInputStream(highScoreFile);
ObjectInputStream ois = new ObjectInputStream(fis);
scores = (Hashtable) ois.readObject();
} catch (Exception e) {
// ignore, try and create new file
}
// if scores is null, create a new hashtable
if (scores == null)
scores = new Hashtable(13);
// update the score and save out the new high score
scores.put(gameName, new Integer(score));
FileOutputStream fos = new FileOutputStream(highScoreFile);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(scores);
oos.close();
return null;
}
});
} catch (PrivilegedActionException pae) {
throw (IOException) pae.getException();
}