Printing output to a file is quite similar to getting input from a file, although the file need not already exist. At the beginning of your source file import java.io.* and throws IOException are needed.
To open the file, here called `file2.out', to write output to:
// Open file to print output to PrintWriter q = new PrintWriter( new FileOutputStream("file2.out"), true);
This line is only needed once when you first want to output to the file. The file will be closed (with the contents saved) automatically when the program ends. Don't forget the true when creating the PrintWriter, or this will not be the case! If the output file already exists when you run the program, e.g. from the last time you ran it, it will be overwritten and lost, so copy or rename files containing output you want to keep, before re-running a program.
Then whenever you want to write data to the file:
q.println("output to be written to file");
The above line can be treated in the same way as System.out.println(), so you can output variable values etc. as usual. With println() data will be written to a new line each time.
Exercise 5.2
Using the techniques described in this section:
Don't forget to write the following at the top of your program:
import java.io.*; import java.text.DecimalFormat;