1
try{
    url = new URL(urls[0]);
    connection = (HttpURLConnection) url.openConnection();
    connection.connect();

    InputStream in = connection.getInputStream();
    InputStreamReader reader = new InputStreamReader(in);

    int data = reader.read();

    while(data != -1){
        char ch = (char) data;
        result+=ch;
        data = reader.read();
    }

    return result;
}catch(Exception e){
    e.printStackTrace();
    return null;
}

Can anyone please explain me the functioning of this code! Because I'm not getting why we use an integer here to store the stream values and how is the while loop is working here.

1
  • You better use reader.readLine() to read line by line. Much more efficient. Much quicker. Commented Feb 7, 2020 at 8:55

2 Answers 2

1

Per the InputStreamReader documentation here, read() returns an integer value of "The character read, or -1 if the end of the stream has been reached". What that means is that read() is reading one character at a time, and if the return value is -1 it means we have reached the end of the stream and the loop condition is now false and exits.

Sign up to request clarification or add additional context in comments.

Comments

0

This code reads in a data input stream character by character.

First you are setting up your input stream:

try{

            url = new URL(urls[0]);

            connection = (HttpURLConnection) url.openConnection();

            connection.connect();

            InputStream in = connection.getInputStream();

            InputStreamReader reader = new InputStreamReader(in);

Then reading the first character of data:

int data = reader.read();

read() returns either the character read (if the read is successful) or the integer value -1 (if the read is unsuccessful), this is why it's used as the condition of the while loop:

while(data != -1){ // while read returns something other than FAIL (-1)

                char ch = (char) data; // Convert the integer value read to a char

                result+=ch; // Append the char to our result string

                data = reader.read(); // read the next value

            }

The rest of your code then returns the result string (all your correctly read chars stuck together) or catches an exception.

            return result;

        }catch(Exception e){

            e.printStackTrace();

            return null;

        }

1 Comment

Thank uou so much. I get it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.