Reversing a File : BufferedReader « File « Java Tutorial






import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class ReverseLines {

  public static void main(String[] args) {
    try {
      BufferedReader input = new BufferedReader(new FileReader(args[0]));
      ArrayList list = new ArrayList();
      String line;
      while ((line = input.readLine()) != null) {
        list.add(line);
      }
      input.close();

      Collections.reverse(list);

      PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter(args[1])));
      for (Iterator i = list.iterator(); i.hasNext();) {
        output.println((String) i.next());
      }
      output.close();
    } catch (IOException e) {
      System.err.println(e);
    }
  }
}








11.31.BufferedReader
11.31.1.BufferedReader
11.31.2.Create BufferedReader from InputStreamReader
11.31.3.Create BufferedReader from FileReader
11.31.4.Read content of a file
11.31.5.Reading Text from a File
11.31.6.Reads a text file and displays it line by line.
11.31.7.Using BufferedReader to read input number from user
11.31.8.Call the static method PressAnykey to keep to DOS window open.
11.31.9.Create PrintWriter from BufferedWriter
11.31.10.Create BufferedReader from StringReader
11.31.11.Create BufferReader from InputStreamReader
11.31.12.Reversing a File