Next: The StringTokenizer class. Up: Text files. Previous: The PrintWriter class.


The BufferedReader class

Constructor method

Like PrintWriter is layered on top of a FileWriter, so the BufferedReader is layered on top of a FileReader.

BufferedReader(FileReader reader)
Creates a BufferedReader that uses reader any time it wants to fetch more characters.

(Just as before, this constructor method actually takes a Reader parameter - and FileReader extends Reader, just as some other classes also extend the abstract class Reader.)

Instance methods

There are just two instance methods worth knowing about in the BufferedReader class.

String readLine() throws IOException
Reads and returns the next line, or returns null if there are no more lines in the file. The line separator is not included in the returned string.

void close() throws IOException
Closes the file.

Example

The following program takes a file name from the command line, reads the file into memory, and then prints it out with the lines in reverse order.

import java.util.*;
import java.io.*;

public class Reverse {
    public static void main(String[] args) {
        BufferedReader file;
        try {
            if(args.length != 1) {
                System.err.println("usage: java Reverse filename");
                return;
            }
            file = new BufferedReader(new FileReader(new File(args[0])));
        } catch(FileNotFoundException e) {
            System.err.println("Error opening file " + args[0]
                + ": " + e.getMessage();
            return;
        }

        Vector lines = new Vector();
        try {
            while(true) {
                String line = file.readLine();
                if(line == null) break;
                lines.addElement(line);
            }
            file.close();
        } catch(IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
            return;
        }

        for(int i = lines.size() - 1; i >= 0; i--) {
            System.out.println(lines.elementAt(i));
        }
    }
}

Next: The StringTokenizer class. Up: Text files. Previous: The PrintWriter class.