【问题标题】:why the snippet is unable to detect the end of line为什么片段无法检测到行尾
【发布时间】:2011-08-13 05:23:11
【问题描述】:
FileReader reader = new FileReader("d:\\UnderTest\\AVS\\tester.txt");
       char ch; 
       int x;
       while( ( x = reader.read() ) != -1 ) {
              // I use the following statement to detect EOL
              if( Character.toString((char)x) == System.getProperty("line.separator") ) {
                  System.out.println("new line encountered !");
              } System.out.print( (char)x );
       }

虽然在tester.txt 中有两个句子写在新行上,但在这段代码中 if 语句永远不会起作用。 为什么呢 ?

【问题讨论】:

    标签: java string eol


    【解决方案1】:

    正如一些人所提到的,系统属性line.separator 可能返回多个字符,例如在 Windows 上,它是 \r\n

    根据您的用例,您最好使用BufferedReader::readLine() 直接读取整行并避免执行手动比较。

    【讨论】:

      【解决方案2】:
      1. System.getProperty("line.separator") 返回什么字符串?是否是多个字符,例如"\r\n"?任何单个字符都不会等于包含多个字符的字符串。
      2. 不过,更根本的是,代码使用== 而不是String.equals()检查字符串是否相等时,切勿使用==。始终使用String.equals()

        FileReader reader = new FileReader("d:\\UnderTest\\AVS\\tester.txt");
        char ch; 
        int x;
        final String linesep = System.getProperty("line.separator");
        while( (x = reader.read()) != -1 )
        {
            if( linesep.equals(Character.toString((char)x)) )
            {
                System.out.println("new line encountered !");
            }
            System.out.print( (char)x );
        }
        

      【讨论】:

        【解决方案3】:

        从您的问题中我不知道是否可能涉及跨平台问题,但平台(如 Unix 和 DOS)之间可识别的换行符存在一些差异,这可能可以解释此问题。我不确定,但我认为记事本使用“/r/n”,您的代码可能无法将其识别为行分隔符。

        看看Wikipedia - newline

        特别是在本节:“不同的换行约定通常会导致在不同类型的系统之间传输的文本文件显示不正确。例如,源自 Unix 或 Apple Macintosh 系统的文件可能显示为在某些 Windows 程序上单行长。相反,在 Unix 系统上查看源自 Windows 计算机的文件时,额外的 CR 可能会在每行的末尾显示为 ^M 或作为第二个换行符。 "

        希望对你有帮助。

        【讨论】:

        • 这就是我使用System.getProperty("line.separator")的原因!
        • @Suhail 但是当您阅读和比较单个字符时,您永远不会检测到多字符 EOL。
        • @Matt Ball 是的,我现在意识到了。
        猜你喜欢
        • 2010-10-25
        • 2016-12-04
        • 2012-01-16
        • 1970-01-01
        • 1970-01-01
        • 2014-12-14
        • 2016-03-08
        • 2017-01-02
        • 2015-06-03
        相关资源
        最近更新 更多