Java Reference
In-Depth Information
filePrefix = prefix;
try {
ObjectInputStream readIn = new ObjectInputStream(
new FileInputStream(prefix + id.toString()));
PlayerImpl copy = (PlayerImpl) readIn.readObject();
readIn.close();
id = playerId;
name = copy.name;
team = copy.team;
pos = copy.pos;
} catch (IOException e) {
System.out.println(
"unable to open file for player, creating new player object");
name = "unknown";
} catch (ClassNotFoundException e) {
System.out.println("unable to read file for player");
}
}
protected void finalize() {
if (readIn != null) {
try {
} catch (Exception e) {
/*if there is an exception on close, we will
* just eat it*/
}
}
if (changed) {
try {
ObjectOutputStream writeOut = new ObjectOutputStream(
new FileOutputStream(filePrefix +
id.toString()));
writeOut.writeObject(this);
writeOut.close();
} catch (Exception e) {
System.out.println("unable to write object");
}
}
}
In this version of the code, we leave the ObjectInputStream that we used to read in our
Player state open. This allows us to reread the state at any time, without having to open the
file again (an operation that can be quite expensive). Instead, we wait until the Player object
is being garbage collected to close the ObjectInputStream , since we know that we won't be
Search WWH ::




Custom Search