Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 8 ■ WRITING AND READING FILES

characters, but we can't count on such things. Instead, we should specify a file name by using Java's path
specifiers, as shown in listing 8-2.
Second, notice that we must handle an exception to work with a File object. Nearly all the methods
in the various Input/Output classes and interfaces throw an IOException. As we learned when we
covered the basics of exceptions in Chapter 2, “Java Syntax,” Java objects generally throw exceptions
whenever something beyond the bounds of your program might cause a problem. In the case of
methods that deal with files, your program cannot anticipate all the things that can go wrong on the file
system. You might inadvertently specify a directory or drive that does not exist or specify an invalid file
name. For example, my laptop has no Z drive. So, if I try to create Z:\test\myFile.txt, the program
fails. Listing 8-2 shows how to create a file with a path that works on any operating system (so long as a
JVM exists for that operating system).


Listing 8-2. Creating an empty file with path specifiers


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);
try {
myFile.createNewFile();
} catch (Exception e) {
System.out.println("Couldn't create " + myFile.getPath());
}
System.out.println("Created " + myFile.getPath());
}
}


Now, no matter what system we run the program on, we get a proper path for our file. If everything
else works (the C drive exists, the test directory exists, our program has permission to write a file in that
location, and so on), we get a new and empty text file where we expect it.


Opening a File


You probably can't get by with just writing new files all the time, so you should know how to open a file
that already exists, too. What opening a file really amounts to is creating a File object that corresponds
to a file on the file system. Then, through that File object, you can do various things to the contents of
the file. We get to manipulating contents later; for now, let's just get a File object for an existing file.
Because we already created myFile.txt, let's get a File object for that file. To make sure we actually
found a file, we use the exists() method to check for a file, as shown in see Listing 8-3.

Free download pdf