与J2me阅读文件混淆。请帮我理解

时间:2011-05-01 04:49:18

标签: file text java-me

我正在为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)。我的理解是,如果我提取一行,我只需要检查换行符。

感谢。

2 个答案:

答案 0 :(得分:1)

请仔细阅读代码文档。你所有的疑惑都得到了很好的回答。

该函数正在检查'-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只是安全检查。

相关问题