2011-05-01 61 views
1

我正在開發用於Symbian S60手機的J2ME應用程序,需要從文本文件讀取數據。我無法訪問BufferedReader從文件中提取一行文本,但我在諾基亞幫助論壇中找到了這一點,這讓我有點困惑。這是代碼,我的問題在下面。謝謝回答。與J2me閱讀文件混淆。請幫助我理解


    /** 
    * Reads a single line using the specified reader. 
    * @throws java.io.IOException if an exception occurs when reading the 
    * line 
    */ 
    private String readLine(InputStreamReader reader) throws IOException { 
     // Test whether the end of file has been reached. If so, return null. 
     int readChar = reader.read(); 
     if (readChar == -1) { 
      return null; 
     } 
     StringBuffer string = new StringBuffer(""); 
     // Read until end of file or new line 
     while (readChar != -1 && readChar != '\n') { 
      // Append the read character to the string. Some operating systems 
      // such as Microsoft Windows prepend newline character ('\n') with 
      // carriage return ('\r'). This is part of the newline character 
      // and therefore an exception that should not be appended to the 
      // string. 
      string.append((char)readChar); 

      // Read the next character 
      readChar = reader.read(); 
     } 
     return string.toString(); 
    } 

我的問題是關於readLine()方法。在while()循環中,爲什​​麼我必須檢查readChar!= -1和!='\ n'?我的理解是-1代表流的結束(EOF)。我的理解是,如果我提取一行,我只需要檢查換行符char。

謝謝。

回答

1

請仔細閱讀代碼文檔。你所有的疑問都在這方面得到了很好的回答。

該函數正在檢查'-1',因爲它正在處理那些沒有換行字符的流。在這種情況下,它會以字符串形式返回整個流。

0

這就是你如何(喜歡)將邏輯應用於你想要做什麼/實現的方式。例如上面的例子可以寫成他的樣子


private String readLine(InputStreamReader reader) throws IOException { 
     // Test whether the end of file has been reached. If so, return null. 
     int readChar = reader.read(); 
     if (readChar == -1) { 
      return null; 
     }else{ 
      StringBuffer string = new StringBuffer(""); 

      // Read until end of file or new line 
      while (readChar != '\n') { 
       // Append the read character to the string. Some operating systems 
       // such as Microsoft Windows prepend newline character ('\n') with 
       // carriage return ('\r'). This is part of the newline character 
       // and therefore an exception that should not be appended to the 
       // string. 
       string.append((char)readChar); 

       // Read the next character 
       readChar = reader.read(); 
      } 
      return string.toString(); 
     } 
    } 

因此,以前的代碼示例readChar檢查-1只是保障檢查。