Java Reference
In-Depth Information
Opening a Text File for Appending
To create an object of the class PrintWriter and connect it to a text file for appending to
the end of the text already in the file, proceed as follows.
SYNTAX
Output_Stream_Name =
new PrintWriter(
new FileOutputStream( File_Name, True_Boolean_Expression ));
EXAMPLE
PrintWriter outputStream;
outputStream =
new PrintWriter( new FileOutputStream("stuff.txt", true ));
After this statement, you can use the methods println and print to write to the file, and
the new text will be written after the old text in the file.
(If you want to create a stream using an object of the class File , you can use a File object
in place of the File_Name . The File class is discussed in the section entitled “The File
Class.”)
When used in this way, the FileOutputStream constructor, and so the PrintWriter con-
structor invocation, can throw a FileNotFoundException , which is a kind of IOException .
Self-Test Exercises
3. What kind of exception might be thrown by the following, and what would it
indicate if this exception were thrown?
PrintWriter outputStream =
new PrintWriter( new FileOutputStream("stuff.txt"));
4. Does the class PrintWriter have a constructor that accepts a string (for a file
name) as an argument, so that the following code would be legal?
PrintWriter outputStream =
new PrintWriter("stuff.txt");
(continued)
Search WWH ::




Custom Search