10.4 Reading and Writing Primitive Values

In following program the file test.txt is opened for reading and the file testavg.txt is opened for writing. The program reads the contents of the first file, calculate average marks of three subjects, and store the results in the second file.

Use Notepad or another text editor to create a simple file that can be used
to test the program. Sample data of file test.txt.

sample test file for reading

Look at the following code :

import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class StudentRecord
    public static void main(String[] args) throws IOException
        // declare and initialize the variables
        double test1, test2, test3;
        double average;
        String name;
        FileReader fr = new FileReader("test.txt");
        Scanner inFile = new Scanner(fr);
        PrintWriter outFile = new PrintWriter("testavg.txt");
        // Read till end of file
while (inFile.hasNext())
{ name = inFile.next(); outFile.println("Student Name: " + name); test1 = inFile.nextDouble(); test2 = inFile.nextDouble(); test3 = inFile.nextDouble(); outFile.printf("Test scores: %5.2f %5.2f %5.2f %n", test1, test2, test3); average = (test1 + test2 + test3) / 3; outFile.printf("Average test score: %5.2f %n", average); outFile.prinntln(); } inFile.close(); outFile.close(); } }

After compiling and running the program, content of testavg.txt file.

file containing test average