Java Reference
In-Depth Information
already exists, the old contents of
stuff.txt
will be lost. If the file
stuff.txt
does not
exist, then a new, empty file named
stuff.txt
will be created.
We want to associate the output stream
outputStream
with the file named
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
FileOutputStream
, which is then used as an argument to a constructor for the class
PrintWriter
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
FileOutputStream
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
FileNotFoundException
, 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 this variable 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
Display 10.1
Sending Output to a Text File
(part 1 of 2)
1
import
java.io.PrintWriter;
2
import
java.io.FileOutputStream;
3
import
java.io.FileNotFoundException;
4
public class
TextFileOutputDemo
5 {
6
public static void
main(String[] args)
7 {
8 PrintWriter outputStream =
null
;
9
try
10 {
11 outputStream =
12
new
PrintWriter(
new
FileOutputStream("stuff.txt"));
13 }
14
catch
(FileNotFoundException e)
(continued)