Java Reference
In-Depth Information
System.out.println("Created a directory called " + testDirectoryName);
}
}
Notice the System.Exit(1) command. That line makes the program stop (to be more precise, it
terminates the currently running Java Virtual Machine) if something bad happens. By convention (and
an old convention, at that), an exit code of 0 indicates that a program stopped normally (that is, without
error). Any other value indicates some kind of error. In the days before detailed exception messages (and
still today in some systems), a cryptic number was all a person got when a program failed. Then
someone would have to look up the number in a list of error codes to find out what happened. Good
system operators knew large numbers of these codes by heart. Developers are happy to get more
meaningful output these days.
As usual, you can see the name of the directory in Eclipse's console. I've also included a screenshot
of the file system after the program runs, just to show that it works. Figure 8-6 shows the directories in
the path field of Windows Explorer on my system.
Figure 8-6. Result of creating three nested directories
Deleting a Directory
Similarly, you might need to delete a directory at some point. As you probably expect by now, the code
for doing so is remarkably similar to the code for creating a directory, as shown in Listing 8-10.
Listing 8-10. Deleting a directory
package com.apress.java7forabsolutebeginners.examples;
import java.io.File;
public class FileTest {
public static void main(String[] args) {
String testDirectoryName = "C:" + File.separator + "test";
File testDirectory = new File(testDirectoryName);
if (testDirectory.exists()) {
testDirectory.delete();
System.out.println("Deleted a directory called " + testDirectoryName);
} else {
System.out.println("Couldn't delete " + testDirectory
+ " because it does not exist");
}
}
}
Search WWH ::




Custom Search