【发布时间】:2011-05-01 04:49:17
【问题描述】:
我正在为 Symbian S60 手机开发 J2ME 应用程序,需要从文本文件中读取。我无法访问 BufferedReader 从文件中提取一行文本,但我确实在诺基亚帮助论坛中找到了这个,这让我有点困惑。这是代码,我的问题在下面。谢谢回答。
/**
* 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)。我的理解是,如果我要提取一行,我应该只需要检查换行符。
谢谢。
【问题讨论】: