JAVA实现从最后一行读取文件

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class FromEndRF {
  puhttp://i.cnblogs.com/EditArticles.aspx?opt=1blic static void main(String args[]) {
    RandomAccessFile rf = null;
    try {
      rf = new RandomAccessFile("d:\\2.txt", "r");
      long len = rf.length();
      long start = rf.getFilePointer();
      System.out.println(start);
      long nextend = start + len - 1;
      String line;
      rf.seek(nextend);
      int c = -1;
      while (nextend > start) {
        c = rf.read();
        if (c == '\n' || c == '\r') {
          line = rf.readLine();
          System.out.println(line);
          nextend--;
        }
        nextend--;
        rf.seek(nextend);
        if (nextend == 0) {// 当文件指针退至文件开始处,输出第一行
          System.out.println(rf.readLine());
        }
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (rf != null)
          rf.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

 

posted @ 2014-07-27 16:13  林一  阅读(2300)  评论(0)    收藏  举报