Java Reference
In-Depth Information
pendent part of the string, and if we just hardcode a \ or a / into our method (depending on
which flavor of operating system we are using for development), our code won't be portable
when moved to a system of a different flavor.
Fortunately, the Java environment gives us a way to deal with this. As part of the File class,
there are static members that allow us to get the filename separator that is used by the system
on which the code is running. We can get the separator either as a character or as a String .
Since we are going to be concatenating this with a couple of other String objects, we will get
the separator as a String . So our first cut at a revised PlayerImpl will have filenaming in the
constructor and the writeState() method that looks like:
public PlayerImpl(UUID playerId, String teamName) {
try {
id = playerId;
ObjectInputStream readIn =
new ObjectInputStream(new FileInputStream(
teamName + File.separator + id.toString()));
PlayerImpl fromDisk = (PlayerImpl) readIn.readObject();
readIn.close();
id = playerId;
name = fromDisk.name;
team = fromDisk.team;
pos = fromDisk.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 writeState() {
try {
ObjectOutputStream writeOut =
new ObjectOutputStream(new FileOutputStream(
team.getName() + File.separator + id.toString()));
writeOut.writeObject(this);
writeOut.close();
changed = false;
} catch (Exception e) {
System.out.println("unable to write object");
Search WWH ::




Custom Search