我正在尝试获取文件的最后一行,但我的输出显示它从未找到它。我还尝试寻找所有行开头的“[”,但除非跳转是完美的,否则程序不会跳过“[”。我尝试寻找“\r\n”、System.getProperty("line.separator")、\r 和 \n。很可能这是一个愚蠢的错误,但如果我有它但我找不到它,那么其他人也可能会遇到它。
RandomAccessFile raf = new RandomAccessFile(fileLocation, "r");
//Finds the end of the file, and takes a little more
long lastSegment = raf.length() - 5;
//**Looks for the new line character \n?**
//if it cant find it then take 5 more and look again.
while(stringBuffer.lastIndexOf("\n") == -1) {
lastSegment = lastSegment-5;
raf.seek(lastSegment);
//Not sure this is the best way to do it
String seen = raf.readLine();
stringBuffer.append(seen);
}
//Trying to debug it and understand
int location = stringBuffer.lastIndexOf("\n");
System.out.println(location);
FileInputStream fis = new FileInputStream(fileLocation);
InputStreamReader isr = new InputStreamReader(fis, "UTF8");
BufferedReader br = new BufferedReader(isr);
br.skip(lastSegment);
System.out.println("br.readLine() " + br.readLine());
}
来自代码的想法来自 快速读取文本文件的最后一行?
我使用的文件是这个 http://www.4shared.com/file/i4rXwEXz/file.html
感谢您的帮助,如果您看到我的代码可以改进的任何其他地方,请告诉我