Saving Games to the Right Destination

So far, your serialized objects and JPEG thumbnails have simply been "dumped" in the current directory. For a quality game, this approach is often not acceptable. Your game's players will appreciate any files generated by the program ending up in neatly organized folders, stored under one root directory that holds all game files. The logical question then becomes, "Where should this root directory be created?" Every Java runtime environment defines a set of system properties that can be accessed via the static System.getProperty() routine:

String getProperty(String propertyName)


The complete list of properties can be obtained by calling the associated getProperties() method (note plural), but for your immediate game-saving needs, all you need to know is that there's one system property called user.home. This String property holds the filing system path for the current user's home directory. On Linux and Mac OS X, this directory will be something like /home/smith. On multiuser Windows systems such as Windows XP or Windows 2000, the directory is something like C:\Documents and Settings\smith, and on older, single-user Windows systems such as Windows 98, the directory is usually C:\WINDOWS. Via user.home, you can create a root game directory to hold all files that the game creates from time to time. Creating directories is achieved with a little help from File.mkdir(). Listing 15.7 shows how to implement this approach.

Listing 15.7 SaveGameState.java
import java.io.*;
class SaveGameState {
private final static String GAME_ROOT = "MyGame";
private final static String SAVED_GAMES = "saved";
private void saveGame() {
 File gameDirectory = createGameDirectory();
 saveGameStateTo(gameDirectory);
}
private File createGameDirectory() {
 String userHome = System.getProperty("user.home");
 File dir = new File(userHome);
 dir = new File(dir, GAME_ROOT);
 if ( ! dir.exists() ) {
 dir.mkdir();
 }
 dir = new File(dir, SAVED_GAMES);
 if ( ! dir.exists() ) {
 dir.mkdir();
 }
 return dir;
}
private void saveGameStateTo(File gameDirectory) {
 // serialize and store all game state objects to specified dir.
}
public static void main (String[] args) {
 new SaveGameState().saveGame();
}
}


The guts of this example is the createGameDirectory() method. You start by finding out where the user's home directory is. From that point in the filing system, you add a new branch and subbranch to the hierarchy, one branch at a time. The end result is a File object pointing at the directory where you can safely and unobtrusively store the game's state.



   
Comments