我是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];
}发布于 2013-01-09 00:43:09
只分配一次缓冲区就足够了,这样你就可以删除循环中的分配,它应该可以很好地工作。
还有一件事。这段代码的性能非常差,因为它在循环中使用了字符串连接。您应该使用StringBuilder.append()而不是s += readString。
附注:我建议你选择另一本书,因为这本书在如此简单的代码中有太多的错误。
发布于 2013-01-09 00:21:56
从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[]。
https://stackoverflow.com/questions/14219175
复制相似问题