简要说明
利用随机读写类RandomAccessFile,读取文本最新的一行字符串
maven依赖
无
样例代码
private String readLastline(File file) throws IOException {
// r 代表只读
try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
String line = null;
//拿到文本最大长度
long length = raf.length();
if (length == 0) return null;
long pos = raf.length() - 1;
int count = 0;
while (pos > 0 && count < 1) {
pos--;
//跳过多少字节
raf.seek(pos);
//跳过后读取一个字段判断是不是换行符
if (raf.readByte() == '\n') {
line = raf.readLine();
//这个判断是为了防止文件末尾不是你想要的信息
//就继续往前搜索
if (!line.contains("your flag")) {
continue;
}
//跳出循环
count++;
}
}
return line;
}