首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >android读取文件

android读取文件
EN

Stack Overflow用户
提问于 2013-01-09 00:08:06
回答 2查看 697关注 0票数 3

我是android的新手,在阅读一本书的时候,我无法理解循环中新分配的原因。在循环之前做一次还不够吗?

代码语言:javascript
复制
        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];
        }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-01-09 00:43:09

只分配一次缓冲区就足够了,这样你就可以删除循环中的分配,它应该可以很好地工作。

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

附注:我建议你选择另一本书,因为这本书在如此简单的代码中有太多的错误。

票数 1
EN

Stack Overflow用户

发布于 2013-01-09 00:21:56

String.copyValueOf javadoc:

代码语言:javascript
复制
  /**
 * 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[]。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14219175

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档