3

我正在尝试获取文件的最后一行,但我的输出显示它从未找到它。我还尝试寻找所有行开头的“[”,但除非跳转是完美的,否则程序不会跳过“[”。我尝试寻找“\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

感谢您的帮助,如果您看到我的代码可以改进的任何其他地方,请告诉我

4

1 回答 1

6

这只是因为您正在使用readline. 它会返回String 不带换行符的行(CR/LF/CRLF)。

Javadoc 或 RandomAccessFile#readLine() 说:

一行文本由回车符 ('\r')、换行符 ('\n')、紧跟换行符的回车符或文件结尾终止。行终止字符被丢弃,并且不包含在返回的字符串中。

如果你试图找到最后一行,你可以读取你的文件直到它结束。

于 2011-09-24T06:10:04.947 回答