Java Reference
In-Depth Information
3. Delete the backup file if it exists.
4. Rename the user's previous file to *.bak .
5. Rename the temporary file to the saved file.
Discussion
As developers, we have to deal with the fact that saving a file to disk is full of risk. There are
many things that can go wrong in saving data, yet it is one of the most critical parts of most
applications. If you lose data that a person has spent hours inputting, or even lost a setting
that a user feels strongly about, she will despise your whole application. The disk might fill
up while we're writing it, or be full before we start. This is a user's error, but we have to face
it. So here's a more detailed discussion of the little five-step dance we should go through:
1. Create a temporary file that we will write to. Set this file to deleteOnExit(true) , so
that if we fail in a later step we don't clutter the disk. Because we are later going to re-
name this file to become the user's real file, and we don't want to run out of disk
space during the rename, it is important that we create the file on the same disk drive
partition (“drive letter” or “mount point”) as the user's real file, otherwise the rename
will silently morph into a copy-and-delete, which could fail due to lack of disk space.
The File API (see Chapter 11 ) makes this easy.
2. Write the user data to this new temporary file. If we are transforming data—say, get-
ting it from a JDBC ResultSet (see Chapter 20 ) or writing objects using a XML trans-
former (see Generating Your Own XML with DOM and the XML Transformer )—an
exception could be thrown. If we're not careful, these exceptions can cause the user's
data to be lost.
3. Delete the backup file if it exists. First time we do this it won't exist; after that it prob-
ably will. Be prepared either way.
4. Rename the user's previous file to *.bak .
5. Rename the temporary file to the save file.
This may seem like overkill, but “It's not overkill, it prevents career kill.” I've done pretty
much this in numerous apps with various save file formats. This plan is the only really safe
way around all the problems that can occur. For example, the final step has to be a rename
not a copy, regardless of size considerations, to avoid the “disk fills up” problem. So, to be
Search WWH ::




Custom Search