Java Reference
In-Depth Information
File Names
The rules for how you spell file names depend on your operating system, not on Java. When
you give a file name to a Java constructor for a stream, you are not giving the constructor
a Java identifier. You are giving the constructor a string corresponding to the file name. A
suffix, such as
.txt
in
stuff.txt
, has no special meaning to a Java program. We are
using the suffix
.txt
to indicate a text file, but that is just a common convention. You can
use any file names that are allowed by your operating system.
A File Has Two Names
Every input file and every output file used by your program has two names: (1) the real file
name that is used by the operating system and (2) the name of the stream that is connected
to the file.
The stream name serves as a temporary name for the file and is the name that is primarily
used within your program. After you connect the file to the stream, your program always
refers to the file by using the stream name.
We said that when you open a text file for writing output to the file, the constructor
might throw a
FileNotFoundException
. But in this situation you want to create a
new file for output, so why would you care that the file was not found? The answer is
simply that the exception is poorly named. A
FileNotFoundException
does not mean
that the file was not found. In this case, it actually means that the file could not be
created. A
FileNotFoundException
is thrown if it is impossible to create the fileāfor
example, because the file name is already used for a directory (folder) name.
IOException
When dealing with file I/O, there are many situations in which your code might throw
an exception of some class, such as
FileNotFoundException
. Many of these various
exception classes are descended classes of the class
IOException
. The class
IOException
is the root class for various exception classes having to do with input and output.
A
FileNotFoundException
is a kind of
IOException
, so a
catch
block for an
IOException
would also work and would look more sensible. However, it is best to
catch the most specific exception that you can, because that can give more information.
As illustrated in Display 10.1 , the method
println
of the class
PrintWriter
works the same for writing to a text file as the method
System.out.println
works
for writing to the screen. The class
PrintWriter
also has the methods
print
and
println
print