2013-01-08 52 views
3

我是刚接触android并在阅读书籍时无法理解循环中新分配的原因。在循环之前做一次还不够吗?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]; 
     } 
+0

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

回答

1

只需分配一次缓冲区就足够了,这样你就可以在循环中删除分配,它应该可以正常工作。

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

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

+0

有趣...它来自于这本书:由Wei-Meng Lee开发的Android 4开发应用程序。 – Leon

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 []。

+0

这是错的吗? (为什么downvote?) – ben75

+0

不,这是正确的 –

+0

downvote?我点击了表示评论有用的按钮。真的很抱歉,如果出了问题。并再次感谢你。 – Leon