Java Reference
In-Depth Information
Opening a Text File for Writing Output
You create a stream of the class PrintWriter and connect it to a text file for writing as follows.
SYNTAX
PrintWriter Output_Stream_Name ;
Output_Stream_Name =
new PrintWriter( new FileOutputStream( File_Name ));
EXAMPLE
PrintWriter outputStream = null ;
outputStream =
new PrintWriter( new FileOutputStream("stuff.txt"));
After this, you can use the methods println and print to write to the file.
When used in this way, the FileOutputStream constructor, and thus the PrintWriter con-
structor invocation, can throw a FileNotFoundException , which is a kind of IOException .
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 suf-
fix .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 sim-
ply 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.
Search WWH ::




Custom Search