【问题标题】:Cant find the newline character in a file (java)在文件中找不到换行符(java)
【发布时间】:2011-09-24 05:29:42
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: java file-io newline fileinputstream random-access


    【解决方案1】:

    这只是因为您使用的是readline。 它会返回String没有换行符(CR/LF/CRLF)。

    Javadoc 或 RandomAccessFile#readLine() 说:

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

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

    【讨论】:

      猜你喜欢
      • 2017-02-28
      • 2018-04-01
      • 2021-12-14
      • 1970-01-01
      • 2018-08-07
      • 1970-01-01
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多