- Note first that all built-in Java classes that have to do with
reading and writing are in the
java.io package, so you have
to do something like
import java.io.*
in the files where you will use these classes.
- To write to a file, the program must open an output stream to the file and create a writer which writes to that stream.
Here is one convenient way to do this:
new PrintWriter(new FileWriter(<filename>,
<append?>));
where filename is a String, and append? is a boolean
specifying whether the program is going to append text to what is already
in the file (if it exists) as opposed to overwrite what is already there.
Note that this code doesn't explicitly create the output stream; this is handled
by the FileWriter class.
- Possible exceptions must be caught for this code. Here is an example of
how this might appear in a method definition.
private void makeWriter() {
try {
System.out.println("Opening output file " +
FILENAME);
outputWriter =
new PrintWriter(new FileWriter(FILENAME, true));
} catch(IOException e) {
System.err.println("MyCanvas: makeWriter: " +
e + ".");
}
}
- To write to the file, you just call one of the write methods in
PrintWriter
or its ancestor classes, for example:
outputWriter.println("Hello there.");
where outputWriter is a variable bound to a PrintWriter.
- The stream must be closed when the program is finished writing to the file.
This can be accomplished with the Writer method
close, which takes
no parameters.