Next: The BufferedReader class. Up: Text files. Previous: FileReader and FileWriter classes.


The PrintWriter class

Using FileWriter for saving into a file is pretty inconvenient: The FileWriter methods take arrays of characters as parameters, but generally we just want to print a value into the file. The java.io library provides class called PrintWriter that we can layer on top of a FileWriter, to work with the file the way we actually want to work.

Constructor method

The constructor method for a PrintWriter takes a FileWriter as a parameter.

PrintWriter(FileWriter writer)
Creates a PrintWriter object that uses writer whenever it wants to actually write something into a file.
A PrintWriter object will build up the character arrays for you, and it pass them along to the FileWriter that you give it in the constructor.

(Technically, the PrintWriter constructor actually takes a Writer object as a parameter, an abstract class which FileWriter extends. There are other classes that also extend the Writer class, and PrintWriter can be layered on top of any of these.)

Instance methods

The PrintWriter instance methods are as follows.

void print(char c)
Prints the single character c.
void print(int i)
Prints the integer i in decimal.
void print(double d)
Prints the floating-point value d.
void print(String s)
Prints the string s.
void print(Object obj)
Prints the string returned by obj.toString().
void close()
Closes the file.
Additionally, the PrintWriter instance methods have a println() method corresponding to each of the print() methods, which prints the data and then terminates the current line of input.

Example

This allows us to save into a file just as conveniently as we can print to the screen. As an example, the following program would create a table of numbers and their square roots.

import java.io.*;

public class SqrtTable {
    public static void main(String[] args) {
        PrintWriter file;
        try {
            if(args.length != 1) {
                System.err.println("usage: java SqrtTable filename");
                return;
            }
            file = new PrintWriter(new FileWriter(new File(args[0])));
        } catch(IOException e) {
            System.err.println("Error opening file " + args[0]
                + ": " + e.getMessage();
            return;
        }

        for(int i = 1; i < 10; i++) {
            file.print(i);
            file.print("  ");
            file.print(Math.sqrt((double) i));
        }
        file.close();
    }
}
Notice how the PrintWriter methods don't throw exceptions, so that the only the process of opening the file needs to go into the try block.


Next: The BufferedReader class. Up: Text files. Previous: FileReader and FileWriter classes.