java - 无法在文件中找到换行符(java)

标签 java file-io newline fileinputstream random-access

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

代码的idea来自 Quickly read the last line of a text file?

我用的文件是这个 http://www.4shared.com/file/i4rXwEXz/file.html

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

最佳答案

这只是因为你正在使用readline。 它返回行 String 没有换行符,不管它是什么 (CR/LF/CRLF)。

Javadoc 或 RandomAccessFile#readLine() 说:

A line of text is terminated by a carriage-return character ('\r'), a newline character ('\n'), a carriage-return character immediately followed by a newline character, or the end of the file. Line-terminating characters are discarded and are not included as part of the string returned.

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

关于java - 无法在文件中找到换行符(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7537250/

相关文章:

java - 如何抑制 Selenium 日志

java - Webview loadurl 崩溃

ruby - Nokogiri to_xml 没有回车

java - Scanner next() - 如何替换换行符 [java]

java - Eclipse 和 Java 3D 错误空图形配置

c - 如何从 NaCl 开发环境应用程序打开文件?

python - 在 python 中列出目录时使用通配符

php - PHP 中的文件 IO 不起作用

tabs - CKEditor 从标题之间删除空格/制表符

java - OOP循环引用