Java Reference
In-Depth Information
In this code, we have replaced the filePrefix that was magically passed in by the code call-
ing the PlayerImpl with code that constructs a real file path. By using the File.separator ,
we ensure that the file path we construct will work on any environment, no matter what separ-
ator is used in filenames in that environment. Using the facilities given us by the libraries and
the runtime, we have made our code portable.
We used the File.separator static field because we were dealing with the filesystem, so
looking in the File class for the String seems like an obvious choice. We could have easily
thought that the abstraction might be something related to the system on which we were run-
ning our program, and therefore gone looking for some way of finding the right character in
the System class. We would have succeeded; we can get the same information using proper-
ties associated with the system. There is a system property named file.separator that we
could have used that would have given us the string needed in our code. If we were to use this
method of obtaining the file separator, our creation of the ObjectInputStream would look
ObjectInputStream readIn =
new ObjectInputStream(new FileInputStream(
teamName + System.getProperty("file.separator")
+ Id.toString()));
and our call to write the player data would look like:
ObjectOutputStream writeOut =
new ObjectOutputStream(new FileOutputStream(
team.getName() + System.getProperty("file.separator")
+ playerId.toString()));
Although getting the separator character for our file path from the environment eliminates one
source of nonportability, we still have gotten only halfway to a solution for our problem. We
now have a way of placing the player data in a directory determined by the team of the player,
but we are still reading from and writing to a relative path. That is, where we look for data and
where we write our data will depend on where the program is run, since the file path that we
are constructing is a relative path. This path will be relative to where the JVM is run, which
Search WWH ::

Custom Search