Java Reference
In-Depth Information
contains a simple program that uses
to send output to a text file. Let's
PrintWriter
look at the details of that program.
All the file I/O related classes we introduce in this chapter are in the package
,
so all our program files begin with import statements similar to the ones in Display 10.1.
The program in Display 10.1 creates a text file named
java.io
java.io
that a person can
read using an editor or that another Java program can read. The program creates an
object of the class
stuff.txt
as follows:
PrintWriter
outputStream =
new PrintWriter( new FileOutputStream("stuff.txt"));
The variable
is of type
and is declared outside the
outputStream
PrintWriter
try
block. The preceding two lines of code connect the stream named
to
outputStream
the file named
. When you connect a file to
a stream in this way, your program always starts with an empty file. If the file
. This is called
opening the file
opening a file
stuff.txt
already exists, the old contents of
will be lost. If the file
stuff.txt
stuff.txt
does not exist, then a new, empty file named
will be created.
stuff.txt
stuff.txt
We want to associate the output stream
with the file named
outputStream
stuff.txt . However, the class PrintWriter has no constructor that takes a file name
as its argument. So we use the class FileOutputStream to create a stream that can be
used as an argument to a PrintWriter constructor. The expression
FileOutput-
Stream
new FileOutputStream("stuff.txt")
takes a file name as an argument and creates an anonymous object of the class File-
OutputStream , which is then used as an argument to a constructor for the class Print-
Writer as follows:
new PrintWriter( new FileOutputStream("stuff.txt"))
This produces an object of the class PrintWriter that is connected to the file
stuff.txt . Note that the name of the file, in this case stuff.txt , is given as a String
value and so is given in quotes.
If you want to read the file name from the keyboard, you could read the name to a
variable of type String and use the String variable as the argument to the FileOut-
putStream constructor.
When you open a text file in the way just discussed, a FileNotFoundException
can be thrown, and any such possible exception should be caught in a catch block.
(Actually, it is the FileOutputStream constructor that might throw the FileNot-
FoundException , but the net effect is the same.)
Notice that the try block in Display 10.1 encloses only the opening of the file.
That is the only place that an exception might be thrown. Also note that the variable
outputStream is declared outside of the try block. This is so that the variable output-
Stream can be used outside of the try block. Remember, anything declared in a block
(even in a try block) is local to the block.
file name
reading the
file name
FileNot-
Found-
Exception
Search WWH ::




Custom Search