Java Reference
In-Depth Information
of these might be thrown. Instances of checked subclasses of
IOException
may be thrown
at times to provide more-detailed diagnostic information, such as
FileNotFoundException
and
EOFException
. From Java 7, a shift is taking place from a number of classes in the
java.
io
package to those in the
java.nio
hierarchy, although without completely superseding eve-
rything in
java.io
. We will introduce some of these new classes alongside the legacy ones.
A full description of the many different classes in the
java.io
and
java.nio
packages is
beyond the scope of this topic, but we shall provide some fundamental examples within the
context of several of the projects we have already seen. This should give you enough back-
ground to experiment with input/output in your own projects. In particular, we shall illustrate
the following common tasks:
■
obtaining information about a file from the file system
■
writing textual output to a file with the
FileWriter
class
■
reading textual input from a file with the
FileReader
and
BufferedReader
classes
■
anticipating
IOException
exceptions
■
parsing input with the
Scanner
class
In addition, we look at reading and writing binary versions of objects as a brief introduction to
Java's
serialization
feature.
For further reading on input/output in Java, we recommend Oracle's tutorial, which can be
found online at:
12.9.1
Readers, writers, and streams
Several of the classes of the
java.io
package fall into one of two main categories: those
dealing with text files and those dealing with binary files. We can think of text files as contain-
ing data in a form similar to Java's
char
type—typically simple, line-based, human-readable
alphanumeric information. Web pages, written in HTML, are a particular example. Binary
files are more varied: image files are one common example, as are executable programs such
as word processors and media players. Java classes concerned with processing text files are
known as
readers
and
writers
, whereas those concerned with binary files are known as
stream
handlers. In the main, we shall focus on readers and writers.
12.9.2 The
File
class and
Path
interface
A file is much more than just a name and some contents. A file will be located in a particular
folder
or
directory
on a particular disk drive, for instance, and different operating systems have
different conventions for which characters are used in file pathnames. The
File
class allows a
program to enquire about details of an external file in a way that is independent of the particular
file system on which the program is running. The name of the file is passed to the constructor of
File
. Creating a
File
object within a program does not create a file in the file system. Rather,
it results in details about a file being stored in the
File
object if the external file exists.
Search WWH ::
Custom Search