Java Reference
In-Depth Information
// If the file doesn't exist
if (!aFile.isFile()) {
// Check the parent directory...
aFile = aFile.getAbsoluteFile();
File parentDir = new File(aFile.getParent());
if (!parentDir.exists()) { // ... and create it if necessary
parentDir.mkdirs();
}
}
// Place to store the stream reference
FileOutputStream outputFile = null;
try {
// Create the stream opened to append data
outputFile = new FileOutputStream(aFile, true);
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
}
System.exit(0);
}
}
After executing this code, you should find that the directories and the file have been created. You can
try this out with paths with a variety of directory levels. Delete them all when you have done, though.
How It Works
We call isDirectory() in the if statement to see whether the path is just a directory. Instead of
aborting at this point we could invite input of a new path from the keyboard, but I'll leave that for you
to try. Next we check whether the file exists. If it doesn't we call getAbsoluteFile() to ensure that
our File object has a parent path. If we don't do this and we have a file specified with a parent, in the
current directory for instance, then getParent() will return null . Having established the File
object with an absolute path, we create a File object for the directory containing the file. If this
directory does not exist, calling mkdirs() will create all the directories required for the path so that we
can then safely create the file stream. The FileOutputStream constructor can in theory throw a
FileNotFoundException although not in our situation here. In any event, we must put the try and
catch block in for the exception.
A further possibility is that you might start with two strings defining the directory path and the file name
separately. You might then want to be sure that you had a valid directory before you created the file.
You could do that like this:
String dirname = "C:/Beg Java Stuff"; // Directory name
String filename = "charData.txt"; // File name
File dir = new File(dirname); // File object for directory
if (!dir.exists()) { // If directory does not exist
if (!dir.mkdirs()) { // ...create it
System.out.println("Cannot create directory: " + dirname);
System.exit(1);
Search WWH ::




Custom Search