java中从末行逐行向上读取文件



// 博客搬家咯~ http://joeleee.github.io/


// 博客搬家咯~ http://joeleee.github.io/


// 博客搬家咯~ http://joeleee.github.io/



1
/**************
2 * Test
3 *
4 * @param args
5 */
6 public static void main(String[] args) {
7 try {
8 // 下面是先写文件, 向文件尾追加, 若文件不存在则自动创建文件
9 FileWriter fw = new FileWriter("C:/test.txt", true); // 用FileWriter打开文件
10 PrintWriter pw = new PrintWriter(fw); // 用写指针加载文件
11 String[] str = { "" }; // 要写入的字符串
12 for (String index : str) {
13 pw.println(index); // 每次都向文件尾追加
14 }
15 pw.close(); // 关闭
16 fw.close(); // 关闭
17
18 // 下面定位文件末行, 一行一行向上读取
19 RandomAccessFile raf = new RandomAccessFile("C:/test.txt", "r"); // 该类可以定位文件,
20 // 是java
21 // IO类中唯一可以用来定位的
22 long len = raf.length(); // 获得文件的长度,以便定位末尾
23 if (len <= 3) { // 判断文件是否为空
24 System.out.println("the flie is NULL!");
25 return;
26 }
27 long pos = len - 1; // 定位文件尾
28 while (pos > 0) { // 判断文件是否到达头
29 --pos; // 一个字符一个字符的向前移动指针
30 raf.seek(pos); // 定位文件指针所指的位置
31 if (raf.readByte() == '\n') { // 如果是换行符,就可以读取该行了
32 System.out.println(raf.readLine());
33 }
34 }
35 raf.seek(pos); // 最后还需要读取第一行
36 System.out.println(raf.readLine());
37 raf.close(); // 关闭
38
39 } catch (FileNotFoundException e) {
40 e.printStackTrace();
41 } catch (IOException e) {
42 e.printStackTrace();
43 }
44 System.exit(0);
45 return;
46 }
From zhuocheng (cnblogs.com/zhuocheng)
原文地址:https://www.cnblogs.com/zhuocheng/p/2351373.html