Welcome to Yumao′s Blog.
現在寫的東西經常都會掛上日誌輸出
但是日誌文本的話是至上而下打印的
那麼一個文本非常巨大的話
一般的文件讀取方式就會很花費時間
所以我們就需要一個能快速的讀取
文本最後一行的方法
基本思路如下:
1.使用RandomAccessFile移至文本末端
2.一點一點的往上移動光標
3.碰到回車”\n” 截取最後一句文本
以下是代碼:
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;
}
}