Java Reference
In-Depth Information
In Java 7, the Path interface in java.nio.file fulfills a similar role. Because Path is an
interface rather than a class, a concrete instance of an implementing class is created via a static
get method of the Paths class (note the plural name), which is also in the java.nio.file
package. When working with legacy code, an equivalent Path object may be created from a
File object via the toPath method of File .
We can sometimes avoid getting into situations that require an exception to be handled, by
using a File or Path object to check whether or not a file exists. A File object has exists
and canRead methods, which make attempting to open a file less likely to fail if we use them
first. However, because opening a file that we know exists still requires a potential exception to
be handled, most people don't bother with checking first.
Path does not itself have equivalent methods. Instead, the Files class (plural, again) provides
a large number of static methods for querying the attributes of a Path object; for instance,
exists , isReadable , isDirectory , etc.
Exercise 12.40 Read the API documentation for the File class from the java.io pack-
age. What sort of information is available on files?
Exercise 12.41 Using a File object, how can you tell whether a file name represents an
ordinary file or a directory (folder)?
Exercise 12.42 Is it possible to determine anything about the contents of a particular file
from the information stored in a File object?
Exercise 12.43 If you are using Java 7, repeat the preceding three exercises using the
Path and Files classes.
12.9.3
File output
There are three steps involved in storing data in a file:
1
The file is opened.
2
The data is written.
3 The file is closed.
The nature of file output means that any of these steps could fail, for a range of reasons, many
completely beyond the application programmer's control. As a consequence, it will be neces-
sary to anticipate exceptions being thrown at every stage.
In order to write a text file, it is usual to create a FileWriter object, whose constructor takes the
name of the file to be written. The file name can be either in the form of a String or a File object.
Creating a FileWriter has the effect of opening the external file and preparing it to receive
some output. If the attempt to open the file fails for any reason, then the constructor will throw
an IOException . Reasons for failure might be that file system permissions prevent a user from
writing to certain files or that the given file name does not match a valid location in the file system.
 
Search WWH ::




Custom Search