Java Reference
In-Depth Information
}
} else if (!dir.isDirectory()) {
System.err.println(dirname + " is not a directory");
System.exit(1);
}
// Now create the file...
If the directory doesn't exist, we call mkdirs() inside the nested if to create it. Since the method
returns false if the directory was not created, this will check whether or not we have indeed managed
to create the directory.
Avoiding Overwriting a File
In some situations, when the file does exist you may not want it to be overwritten. Here is one way you
could avoid overwriting a file if it already exists:
String filename = "C:/Beg Java Stuff/myFile.txt";
File aFile = new File(filename);
FileOutputStream outputFile = null; // Place to store the stream reference
if (aFile.isFile()) {
System.out.println("myFile.txt already exists.");
} else {
// Create the file stream
try {
// Create the stream opened to append data
outputFile = new FileOutputStream(aFile);
System.out.println("myFile.txt output stream created");
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
}
}
Of course, if you want to be sure that the path will in fact result in a new file being created when it
doesn't already exist, you would need to put in the code from the previous example that checks out the
parent directory. The fragment above avoids overwriting the file but it is not terribly helpful. If the file
exists, we create the same FileOutputStream object as before, but if it doesn't, we just toss out an
error message. In practice, you are more likely to want the program to take some action so that the
existing file is protected but the new file still gets written. One solution would be to rename the original
file in some way if it exists, and then create the new one with the same name as the original. This takes a
little work though.
Try It Out - Avoid Overwriting a File
Without worrying about plugging in the code that ensures that the file directory exists, here is how we
could prevent an existing file from being overwritten.
import java.io.File;
import java.io.FileOutputStream;
Search WWH ::




Custom Search