Writing to a file (Optional)

You've seen how reading text from a file was not very different from reading from System.in. Only the construction of our Scanner changed. Similarly, writing to a text file is not much different from writing to System.out. We use a class called PrintWriter, which has the same methods, such as println and print, as System.out. We can construct an instance of PrintWriter by specifying the file we want to write to.

You can create your own text editor with just a few lines of code. This program will read from System.in and write whatever you type to a file called mydocument.txt:


import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class TextEditor
{
  public static void main(String[] args) throws FileNotFoundException
  {
    Scanner in = new Scanner(System.in);
    File outFile = new File("mydocument.txt");
    PrintWriter out = new PrintWriter(outFile);

    // Echo keyboard input out to the file.
    while (in.hasNextLine())
    {
      String line = in.nextLine();
      out.println(line);
    }
    
    System.out.println("Done");
    out.close(); // Important: don't forget to close!
  }
}

Run this code, click in the Console pane, and type a few lines of input. Hit Control-Z (Control-D on OS X or Linux) to end the input. Remember you may have to click outside the Console pane and click back for this to work in Eclipse. If you are using Eclipse, the file should end up in your project directory.

Then, find the file using Windows File Explorer (or OS X Finder) and take a look at the it and make sure it has the lines you typed. (If the file is blank, make sure you remembered to close the PrintWriter.)

Notice that if named file doesn't already exist, it is created for you when you instantiate the PrintWriter. However:

BE CAREFUL: if you specify the name of a file that already exists, its contents will be destroyed when you create the PrintWriter!

To avoid clobbering an existing file, you can always use the exists() method of the File class to check whether there is already a file with that name. For example:

    Scanner in = new Scanner(System.in);
    File outFile = new File("mydocument.txt");
    if (outFile.exists())
    {
      System.out.print("File already exists, ok to overwrite (y/n)? ");
      if (!in.nextLine().startsWith("y"))
      {
        return;
      }
    }