使用RandomAccessFile , 从后找最后一行数据
public static String readLastLine(File file) throws IOException {
RandomAccessFile raf = new RandomAccessFile(file, "r");
long len = raf.length();
String lastLine = "";
if (len != 0L) {
long pos = len - 1;
while (pos > 0) {
pos--;
raf.seek(pos);
if (raf.readByte() == '\n') {
lastLine = raf.readLine();
break;
}
}
}
raf.close();
return new String(lastLine);
}
使用RandomAccessFile , 从后找最后n行数据
RandomAccessFile raf = null;
File tf = new File(“PATH\OF\THE\DOCUMENT”);
if (tf.exists() && tf.canRead()) {
raf = new RandomAccessFile(tf, “r”);
long len = raf.length();
long pos = len - 1;
if (len > 0L) {
int l = 0;
while (pos > 0 && l < n) {
pos–;
raf.seek(pos);
if (raf.readByte() == ‘\n’) {
l = l + 1;
}
}
}
}
byte[] bytes = new byte[(int) (len - pos)];
raf.read(bytes);
String lines = new String(bytes, “utf-8”);
String[] split = lines.split(“\n”);//split就是最后6行的数据