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, becausereaddoes 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
StringBufferthat didn’t actually come from theReader(probably either0or values written by previousread()calls).