Java Reference
In-Depth Information
Deleting Multiple Directories
If you use the mkdirs method and the JVM can't create the final directory, it might create some of the
directories along the way. That's a problem, so you need to check for each directory in the chain and
remove it. For that reason, paths are sometimes stored as a collection of individual values (perhaps in an
array of String objects), so that they can be worked through programmatically. In cases where not
making empty directories matters (and it always matters, because it's bad form to clutter up the user's
drive), it's best to store the bits of the path as a collection and create each one individually, stopping and
removing any directories that get created if one fails. Consequently, we wouldn't use the mkdirs method
if we care about removing path fragments after a failed directory creation attempt. Listing 8-11 shows a
small program to create directories until one fails and then remove any that might be created along
the way.
Note If you still have a directory called test on your C drive, remove it before running the code in Listing 8-11.
Listing 8-11. Rolling back directories when creating a path fails
package com.apress.java7forabsolutebeginners.examples;
import java.io.File;
public class FileTest {
public static void main(String[] args) {
String currentPath = "C:";
// a double colon is illegal on my Windows machine, so this fails
String[] pathParts = {"test", "test2", "test3::fail"};
for (String pathPart: pathParts) {
currentPath += File.separator + pathPart;
File testDirectory = new File(currentPath);
if (!testDirectory.mkdir()) {
System.out.println("Failed to create " + testDirectory
+ "; removing all created directories");
removePathByParts("C:", pathParts);
} else {
System.out.println("Created " + testDirectory);
}
}
}
private static void removePathByParts(String pathStart, String[] pathParts) {
String currentPath = pathStart;
String[] paths = new String[pathParts.length];
// First, build an array of possible paths
Search WWH ::




Custom Search