Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 8 ■ WRITING AND READING FILES


Listing 8-3. Getting a File object for an existing file

package com.apress.java7forabsolutebeginners.examples;

import java.io.File;

public class FileTest {

public static void main(String[] args) {
String fileName = "C:" + File.separator +
"test" + File.separator + "myFile.txt";
File myFile = new File(fileName);
System.out.println(fileName + " exists? " + myFile.exists());
}
}

Notice how the creation of a File object is the same, regardless of whether the file exists or not. As
we saw earlier in this chapter, a File object is not a file. A File object is a path specification (which might
or might not exist on the file system) and some other information that might or might correspond to an
actual file. Just specifying a path and creating a new File object for it does not create a new file or prove
an existing file exists. To do that, we have to take further steps, as shown in Listings 8-1 and 8-2 (where
we used the createnewFile() method) and Listing 8-3 (where we used the exists() method).

Deleting a File


Sometimes, you need to delete a file, too. The process parallels that of creating a new or finding an
existing file. Listing 8-4 shows the simplest way to do it.

Listing 8-4. Deleting a file

package com.apress.java7forabsolutebeginners.examples;

import java.io.File;
import java.io.IOException;

public class FileTest {

public static void main(String[] args) throws IOException {
String fileName = "C:" + File.separator +
"test" + File.separator + "myFile.txt";
File myFile = new File(fileName);
if(!myFile.exists()) {
throw new IOException("Cannot delete " + fileName
+ " because" + fileName + " does not exist");
} else {
myFile.delete();
}
System.out.println(fileName + " exists? " + myFile.exists());
}
}
Free download pdf