Reputation: 3
I don't really understand what this piece of code does. I mainly want to know what isr.read(inputBuffer)
processes and what the while
loop does. Could someone explain it for me? Thanks.
InputStreamReader isr = new InputStreamReader(is);
int charRead;
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while((charRead = isr.read(inputBuffer)) > 0) {
String readString = String.copyValueOf(inputBuffer, 0, charRead);
XMLContents += readString;
inputBuffer = new char[BUFFER_SIZE];
}
return XMLContents;
} catch(IOException e) {
e.printStackTrace();
return null;
}
Upvotes: 0
Views: 184
Reputation: 371
Basically, the isr.read(inputBuffer)
, reads from the inputstreamreader
, stores the characters to the given fixed size buffer (inputBuffer
), and returns the count of characters read.
The while clause while((charRead = isr.read(inputBuffer)) > 0)
does exactly the explained above, and after the value of the read characters is stored, it checks if it is greater than 0… If so, this means that we have read something from the stream and we enter the loop.
The String.copyValueOf(inputBuffer, 0, charRead);
is used to copy the content of the buffer, into a string object - readString
. After that, this last string object is attached to the XMLContents
object. At the end, a new buffer array object is created and assigned to the inputBuffer
, and the process is repeated.
When no more characters are read, sir.read(inputBuffer)
returns 0
and the value of charRead
is 0
(not greater than 0
). The while
loop is finished and the XMLContents
object is returned.
Upvotes: 2