Java File I/O

This example shows you a simple way to read and write from files using the following classes:

  1. FileReader/BufferedReader: FileReader opens a file for input and BufferedReader wraps it so that buffered reading is performed
  2. Scanner: The BufferedReader's readLine method reads a line at a time. This line is input to a Scanner object, which tokenizes it
  3. FileWriter/BufferedWriter/PrintWriter:

The example reads lines from a file, formats them, and writes them to an output file. The lines have the form:

age true/false
where true/false is a person's guess as to whether or not the age is correct. For example:
40 true
35 false
7 true
The corresponding output would be:
age =   40 correct = true
age =   35 correct = false
age =    7 correct = true
The program takes the input file as a command line argument and hard codes the output file.

The Example Program

import java.util.*;

public class fileio {

    public static void main(String[] args) throws IOException {
	  BufferedReader input_reader;
	  Scanner line_scanner;
	  PrintWriter fw;
          int age;
          boolean correct;

          input_reader = new BufferedReader(new FileReader("data.txt"));
  	  fw = new PrintWriter(
			new BufferedWriter(
				new FileWriter("test.txt")));

	  // readLine() returns null when it reaches EOF
	  while ((nextLine = input_reader.readLine()) != null) {
	    // if the user hit return after the last line of the file,
	    // then there is an empty last line and the while condition
	    // will appear to succeed. The next if statement
	    // caters to that possibility and gets us out of the
	    // loop if there is an empty last line
	    if (nextLine.equals("")) break;
	    line_scanner = new Scanner(nextLine);
	    age = line_scanner.nextInt();
	    correct = line_scanner.nextBoolean();
            fw.format("age = %4d correct = %b%n", age, correct);