Welcome to Yumao′s Blog.
使用Java快速讀取文本最後一行內容
, 2013年03月21日 , Java Language , 评论 在〈使用Java快速讀取文本最後一行內容〉中留言功能已關閉 ,

現在寫的東西經常都會掛上日誌輸出
但是日誌文本的話是至上而下打印的
那麼一個文本非常巨大的話
一般的文件讀取方式就會很花費時間
所以我們就需要一個能快速的讀取
文本最後一行的方法

基本思路如下:
1.使用RandomAccessFile移至文本末端
2.一點一點的往上移動光標
3.碰到回車”\n” 截取最後一句文本

以下是代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package name.yumao.utils;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
 
public class LastLineReadUtils {
    public static String readLastLine(File file, String charset) throws IOException {
      if (!file.exists() || file.isDirectory() || !file.canRead()) {
        return null;
      }
      RandomAccessFile raf = null;
      try {
        raf = new RandomAccessFile(file, "r");
        long len = raf.length();
        if (len == 0L) {
          return "";
        } else {
          long pos = len - 1;
          while (pos > 0) {
            pos--;
            raf.seek(pos);
            if (raf.readByte() == '\n') {
              break;
            }
          }
          if (pos == 0) {
            raf.seek(0);
          }
          byte[] bytes = new byte[(int) (len - pos)];
          raf.read(bytes);
          if (charset == null) {
            return new String(bytes);
          } else {
            return new String(bytes, charset);
          }
        }
      } catch (FileNotFoundException e) {
      } finally {
        if (raf != null) {
          try {
            raf.close();
          } catch (Exception e2) {
          }
        }
      }
      return null;
    }
}
关键字:, , , , ,

评论已关闭