0
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 );
       }

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

4

3 回答 3

2

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

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

于 2011-08-13T05:40:44.063 回答
1
  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 );
    }
    
于 2011-08-13T05:34:42.750 回答
0

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

看看维基百科 - 换行符

特别是在本节:“不同的换行约定通常会导致在不同类型的系统之间传输的文本文件显示不正确。例如,源自 Unix 或 Apple Macintosh 系统的文件可能会在某些 Windows 上显示为单个长行_

我希望这会有所帮助。

于 2011-08-13T05:33:31.620 回答