Page 641 - Introduction to Programming with Java: A Problem Solving Approach
P. 641
15.3 Text-FileOutput 607
/****************************************************************
*
WriteTextFile2.java
Dean & Dean
This appends data to an existing text file.
****************************************************************/
*
*
*
import java.util.Scanner;
import java.io.*;
public class WriteTextFile2
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
PrintWriter fileOut;
String text = "Hello, world!";
try
{
}
// end WriteTextFile2 class
}
// end main
}
System.out.print("Enter filename: ");
fileOut =
new PrintWriter(new FileWriter(stdIn.nextLine(), true));
fileOut.prAipntalng(toext)P; DF Enhancer fileOut.close();
}
catch (IOException e)
{
System.out.println("IO: " + e.getMessage());
value passed to
boolean append
parameter
IOException needed for FileWriter also catches FileNotFoundException.
Figure 15.3 WriteTextFile2 program for appending text to an existing file
but there is a FileWriter constructor that does. So instead of using the PrintWriter constructor which automatically instantiates a FileWriter object that never appends, you can explicitly construct a FileWriter object that can append. Then you can pass it to an overloaded PrintWriter constructor which has a Writer parameter type. Since the FileWriter class is a descendant of the Writer class, this other PrintWriter constructor accepts a FileWriter object as its argument.
The second parameter in the FileWriter constructor is a boolean which tells the computer whether you want to append or not. Using true says you want to append. If you wanted, you could use this more elaborate file opening statement to create a new file or completely overwrite an existing out- put file by using false for the second argument in the FileWriter constructor. Note that this alter- nate way of opening a text file for output requires a more generic catch to catch either PrintWriter’s FileNotFoundException or an IOException thrown by the FileWriter constructor. (The PrintWriter constructor used in Figure 15.2 catches FileWriter’s IOException internally.)