0

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;
}
ByteHamster
  • 4,884
  • 9
  • 38
  • 53
ShroudDx
  • 3
  • 2
  • The `read()` method which is used here, reads the bytes and stores them the characters in the given array. The method returns the "The number of characters read, or -1 if the end of the stream has been reached" (quote vom javadoc). This way the loop continues as long as there is something more to read. – Ria Apr 12 '15 at 09:53

1 Answers1

2

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.

willoller
  • 7,106
  • 1
  • 35
  • 63
ivtoto
  • 241
  • 1
  • 9
  • Note that `inputBuffer = new char[BUFFER_SIZE];` is completely unnecessary, and is just a waste of time. The exception handling of the method is awful as well. – JB Nizet Apr 12 '15 at 10:16