简体   繁体   English

输入流和输入流阅读器

[英]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.因为我不明白为什么我们在这里使用整数来存储流值以及 while 循环在这里是如何工作的。

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".根据此处的 InputStreamReader 文档, read()返回一个整数值“读取的字符,如果已到达流的末尾,则返回 -1”。 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.这意味着read()读取一个字符,如果返回值为 -1 则意味着我们已经到达流的末尾并且循环条件现在为假并退出。

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:阅读()回的字符读取(如果读取成功)或整数值-1(如果读取不成功),这就是为什么它用作while循环的条件:

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;

        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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