我正在为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)。我的理解是,如果我提取一行,我应该只检查换行符。
谢谢。
请仔细阅读代码文档。你所有的疑问都得到了很好的回答。
函数正在检查' -1 ',因为它正在处理那些没有新行字符的流。在这种情况下,它将返回整个流作为字符串。
这只是你如何(喜欢)将逻辑应用到你试图做/实现的事情。例如,上面的例子可以写成他的
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只是安全检查