Java Reference
In-Depth Information
If the file cannot be opened, the constructor will throw a FileNotFoundException , which won't be
very convenient in most circumstances. We must put the call to the constructor in a try block and
catch the exception if we want the code to compile, unless of course we arrange for the method
containing the constructor call to pass on the exception with a throws clause. The exception will be
thrown if the path refers to a directory rather than a file, or if the parent directory in the path does not
exist. If the file does not exist, but the directory that is supposed to contain it does exist, the constructor
will create a new file for you. Creating a File object first enables you to check the file out and deal
with any potential problems. Let's look at ways in which you can apply this.
Ensuring a File Exists
Let's suppose that you want to append data to a file if it exists, and create a new file if it doesn't. Either
way, you want to end up with a file output stream to work with. You will need to go through several
checks to achieve this:
Use the File object to verify that it actually represents a file rather than a directory. If it
doesn't, you can't go any further so output an error message.
Use the File object to decide whether the file exists. If it doesn't, ensure that you have a
File object with an absolute path. You need this to obtain and check out the parent
directory.
Get the path for the parent directory and create another File object using this path. Use the
new File object to check whether the parent directory exists. If it doesn't, create it using the
mkDirs() method for the new File object.
Let's look at how that might be done in practice.
Try It Out - Ensure that a File Exists
You could guarantee a file is available with the following code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class GuaranteeAFile {
public static void main(String[] args) {
String filename = "C:/Beg Java Stuff/Bonzo/Beanbag/myFile.txt";
File aFile = new File(filename); // Create the File object
// Verify the path is a file
if (aFile.isDirectory()) {
// Abort after a message
// You could get input from the keyboard here and try again...
System.out.println("The path " + aFile.getPath()
+ " does not specify a file. Program aborted.");
System.exit(1);
}
Search WWH ::




Custom Search