安卓从文件读取数据

3

我是Android的新手,在阅读一本书时,无法理解循环中为什么需要新的分配。在循环之前进行一次分配不足以满足需求吗?

        FileInputStream fIn =
                openFileInput("textfile.txt");
        InputStreamReader isr = new
                InputStreamReader(fIn);
        char[] inputBuffer = new char[READ_BLOCK_SIZE];
        String s = "";
        int charRead;
        while ((charRead = isr.read(inputBuffer))>0)
        {
            //---convert the chars to a String---
            String readString =
            String.copyValueOf(inputBuffer, 0,
            charRead);
            s += readString;
            inputBuffer = new char[READ_BLOCK_SIZE];
        }

只是为了澄清:问题是为什么在循环中需要以下行:inputBuffer = new char[READ_BLOCK_SIZE]; - Leon
2个回答

3

来自 String.copyValueOf javadoc的内容:

  /**
 * Creates a new string containing the specified characters in the character
 * array. Modifying the character array after creating the string has no
 * effect on the string.
 *
 * @param start
 *            the starting offset in the character array.
 * @param length
 *            the number of characters to use.

因此,在循环中没有必要创建一个新的char[]。


踩?我点击了按钮,上面写着这条评论很有用。如果出了什么问题,真的很抱歉。再次感谢您。 - Leon
@Leon,你没有点踩,但是要关闭一个答案,你必须打勾(在投票下面的清晰勾号)。建议你这样做,因为它鼓励人们回答你的问题。 - cjds

1

只需要分配缓冲区一次,所以您可以在循环内删除分配并且它应该能正常工作。

还有一件事... 这段代码的性能非常差,因为它在循环中使用字符串串联。你应该使用 StringBuilder.append() 而不是 s += readString

P.S. 我建议你选择另一本书,因为这本书在这么简单的代码中有太多的错误。


有趣...这来自于《Android 4应用开发入门》一书,作者是李卫民。 - Leon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接