Same loop giving different output. Java IO
I am facing a very strange problem where the same loop keeps giving me different different output on开发者_高级运维 change of value of BUFFER
final int BUFFER = 100;
char[] charArr = new char[BUFFER];
StringBuffer objStringBuffer = new StringBuffer();
while (objBufferedReader.read(charArr, 0,BUFFER) != -1) {
objStringBuffer.append(charArr);
}
objFileWriter.write(objStringBuffer.toString());
When i change BUFFER size to 500 it gives me a file of 7 kb when i change BUFFER size to 100000 it gives a file of 400 kb where the contents are repeated again and again. Please help. What should i do to prevent this?
You must remember the return value of the read()
call, because read
does not guarantee that the entire buffer has been filled.
You will need to remember that value and use it in the append call to only append that many characters.
Otherwise you'll append un-initialized characters to the StringBuffer
that didn't actually come from the Reader
(probably either 0
or values written by previous read()
calls).
精彩评论