Next: The BufferedReader class. Up: Text files. Previous: FileReader and FileWriter classes.
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.
The constructor method for a PrintWriter takes a FileWriter as a parameter.
(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.)
The PrintWriter instance methods are as follows.
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.
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.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(); } }
Next: The BufferedReader class. Up: Text files. Previous: FileReader and FileWriter classes.