Page 640 - Introduction to Programming with Java: A Problem Solving Approach
P. 640

                606 Chapter 15 Files
 /******************************************************
*
WriteTextFile.java
Dean & Dean
This writes a string to a text file.
******************************************************/
*
*
*
import java.util.Scanner;
import java.io.*;
public class WriteTextFile
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
PrintWriter fileOut;
String text = "Hello, world!";
try
{
   System.out.print("Enter filename: ");
fileOut = new PrintWriter(stdIn.nextLine());
fileOut.println(text);
Open the file.
Write to the file.
       fileOut.close(A);pago PDF Enhancer Close the file.
    }
  catch (FileNotFoundException e)
  {
for PrintWriter constructor call System.out.println("Error: " + e.getMessage());
  }
// end WriteTextFile class
}
// end main
}
Figure 15.2 WriteTextFile program for writing text to a new file or overwriting an old file
the file’s write operation(s) might not be saved to the file. Also, if you forget to close a file, system resources remain allocated to the open file, and that causes system performance to degrade.
Appending Data to an Existing File
Suppose you already have data in an existing file and you would like to add data to it. To append new data to an existing file, you call a PrintWriter constructor, as before, but you have to get some help from a FileWriter object. Specifically, you have to pass a FileWriter object to the PrintWriter con- structor. To see what we’re talking about, examine the PrintWriter instantiation code in Figure 15.3.
To open a file for text output in append mode, all you need to do is write the fileOut = statement shown in Figure 15.3. You don’t have to know why it is the way it is. But if you’re curious, here’s an ex- planation: None of the various overloaded PrintWriter constructors includes an append parameter,


























































   638   639   640   641   642