繁体   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;
}

谁能解释一下这段代码的功能! 因为我不明白为什么我们在这里使用整数来存储流值以及 while 循环在这里是如何工作的。

根据此处的 InputStreamReader 文档, read()返回一个整数值“读取的字符,如果已到达流的末尾,则返回 -1”。 这意味着read()读取一个字符,如果返回值为 -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();

阅读()回的字符读取(如果读取成功)或整数值-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

            }

然后,其余代码返回结果字符串(所有正确读取的字符粘在一起)或捕获异常。

            return result;

        }catch(Exception e){

            e.printStackTrace();

            return null;

        }

暂无
暂无

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

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