Next: The StringTokenizer class. Up: Text files. Previous: The PrintWriter class.
Like PrintWriter is layered on top of a FileWriter, so the BufferedReader is layered on top of a FileReader.
There are just two instance methods worth knowing about in the BufferedReader class.
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.