Java android从文件中读取
我是android新手,在阅读一本书的时候,我不理解在循环中进行新分配的原因。在循环之前做一次还不够吗Java android从文件中读取,java,android,Java,Android,我是android新手,在阅读一本书的时候,我不理解在循环中进行新分配的原因。在循环之前做一次还不够吗 FileInputStream fIn = openFileInput("textfile.txt"); InputStreamReader isr = new InputStreamReader(fIn); char[] inputBuffer = new char[READ_BL
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];
}
从
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.
因此,没有理由在循环中创建一个新的字符[]。只分配一次缓冲区就足够了,这样您就可以删除循环中的分配,它应该可以正常工作 还有一件事。。。这段代码的性能非常差,因为它在循环中使用字符串连接。您应该使用
StringBuilder.append()
而不是s+=readString
另外,我建议您选择另一本书,因为这本书在这样简单的代码中有太多错误。只是为了澄清:问题是为什么循环中需要以下行:inputBuffer=new char[READ_BLOCK_SIZE];否决票?我点击了按钮,上面写着评论很有用。如果出了问题,我真的很抱歉。再次感谢你。@Leon你没有否决投票,但要结束一个答案,你必须勾选它(投票下面的清晰勾号)。建议你这样做,因为它鼓励人们回答你的问题。。。这本书出自李伟(Wei Meng Lee)的《开始Android 4应用程序开发》。