next up previous contents
Next: 6 Multiple methods Up: 5 More advanced input Previous: Input from a file   Contents

Output to a file

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


(6 marks)



Using the techniques described in this section:

(i)
Write a program that will read in numbers from a given file and print them on the screen. Use the file input.txt as input which you can download from
http://www.pp.rhul.ac.uk/~george/PH2150/downloads/input.txt.
Include your program output in your lab book.

(ii)
Modify the program to write the numbers out to a different file, in scientific format with 6 significant figures, e.g. 3.2 is written as 3.20000E00, 0.5 is written as 5.00000E-01. Include the program listing and a printout of the output file in your note book.

Don't forget to write the following at the top of your program:

import java.io.*;
import java.text.DecimalFormat;




next up previous contents
Next: 6 Multiple methods Up: 5 More advanced input Previous: Input from a file   Contents
RHUL Dept. of Physics