简体   繁体   中英

Input Stream & Input Stream Reader

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.

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.

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;

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM