Java I/O How to - Read a text file from the back








Question

We would like to know how to read a text file from the back.

Answer

// w  w w .  ja  va2 s  . c o m
import java.io.File;
import java.io.FileReader;

public class Main {
  public static void main(String[] args) throws Exception {
    File f = new File("Main.java");
    FileReader fr = new FileReader(f);

    char[] c = new char[(int) f.length()];
    char[] cnew = new char[(int) f.length()];
    StringBuffer sbuf = new StringBuffer();
    fr.read(c, 0, (int) f.length());

    int len = (int) f.length();

    for (int i = 0, j = len - 1; i < len; i++, j--) {
      cnew[i] = c[j];
      sbuf.append(cnew[i]);
    }

    System.out.println(sbuf.toString());
    fr.close();

  }
}

The code above generates the following result.