Java Reference
In-Depth Information
for (int pathCounter = 0; pathCounter < pathParts.length; pathCounter++) {
currentPath += File.separator + pathParts[pathCounter];
paths[pathCounter] = currentPath;
}
// Then work backwards, checking for the existence of each path
// and deleting each one if we find it
for (int pathCounter = pathParts.length - 1; pathCounter >= 0;
pathCounter--) {
File currentFile = new File(paths[pathCounter]);
if (currentFile.delete()) {
System.out.println("Removed " + currentFile);
}
}
}
}
As you can see, fixing a failed mkdirs run takes a bit of doing. (Of course, there might be better ways
to solve this problem.) Ever have a software installation fail and then notice that you have directories left
behind? It's because rolling back a path is a pain in almost every programming language, and some folks
don't bother, even for commercial software.
Figure 8-7 shows the output from trying to create a directory with an impossible name and the
process of rolling back the directory creation options.
Figure 8-7. Rolling back a failed directory creation operation
Writing and Reading Content
We covered quite a bit of ground without ever writing or reading a single byte to or from a file. It often
happens in software development that you must invest the time to understand one thing before you can
understand another thing. Nearly all fields of study have enough complexity to require learning
prerequisite information, and software development works that way, too. As Bill Cosby once quipped, “I
had to tell you that joke before I could tell you this joke.”
Merrily Down the Stream
In Java (and some other languages), reading from and writing to a file relies on the use of a structure
called a stream . A stream is the data going to or coming from the file with some metadata (that is, data
about the data) to indicate information such as how many bytes are available (in a file being read),
whether the data is inbound or outbound, the file descriptor for the file in question, and so on. We do a
bit more with streams (because we use a different kind of stream) when we process XML files in the next
chapter. For now, just remember that a stream is the data structure that holds the content going to or
coming from our file.
Search WWH ::




Custom Search