2011-08-13 34 views
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個句子寫在新行上。 這是爲什麼呢?爲什麼片段無法檢測到行尾

回答

2

如一些人所提到的,系統屬性line.separator可能會返回一個以上的字符,例如在Windows上,它是\r\n

根據您的使用情況,最好使用BufferedReader::readLine()來直接讀取整個行,並避免執行手動比較。

0

我不知道你的問題是否可能涉及跨平臺問題,但是在可能解釋這個問題的平臺(例如Unix和DOS)之間的已識別換行字符有一些差異。我不確定,但我認爲記事本使用「/ r/n」,可能無法將您的代碼識別爲行分隔符。

看一看Wikipedia - newline

並且具體在本節:「不同的換行符約定常引起已不同類型的系統之間傳送文本文件被錯誤地顯示例如,文件始發於Unix。或Apple Macintosh系統可能在某些Windows程序中顯示爲單個長行,反之,在Unix系統上查看源自Windows計算機的文件時,額外的CR可能在每行的末尾顯示爲^ M或作爲第二次換行

我希望有幫助。

+0

這就是我使用'System.getProperty(「line.separator」)''的原因! –

+0

@Suhail,但是當你閱讀和比較單個字符時,你永遠不會檢測到多字符EOL。 –

+0

@馬特球是的,我現在意識到。 –

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); 
    } 
    
相關問題