A coworker of mine got puzzled with the
StringIndexOutOfBoundsException yesterday morning while she was trying to write string to the
BufferedWriter. She claimed that the total length of the text she wanted to write was just only 255 characters of the entire buffer and it wasn't going to exceed the length of the buffer itself. Something like this:
buffer length: 1000 characters
the length of string she wanted to write: 255 characters
and the original code:
write(buffer, 700, 955);
"See? 955 is not yet reaching the length of the buffer, which is 1000, why am I getting that exception?"
Perhaps she get too used to the
String.substring API:
public String substring(int beginIndex, int endIndex)
Parameters:
beginIndex - the beginning index, inclusive.
endIndex - the ending index, exclusive.
After reading through the
BufferedWriter.write API with her:
public void write(char[] cbuf, int off, int len) throws IOException
Parameters:
cbuf - A character array
off - Offset from which to start reading characters
len - Number of characters to write
We started looking at each other embarrassingly, the original code was actually trying to write 955 characters from the offset 700, rather than write until reaching character 955. The correct one should be:
write(buffer, 700, 255);
Just another example of not reading documentation before coding.