简体   繁体   English

在java中从InputStream获取数据

[英]Fetching data from InputStream in java

I am trying to fetch data from InputStream using InputStreamReader and my code is given below.我正在尝试使用 InputStreamReader 从 InputStream 获取数据,我的代码如下。

protected String doInBackground(String... urls) {
    String result = "";
    URL url;
    HttpURLConnection urlConnection = null;

    try {
        url = new URL(urls[0]);
        urlConnection = (HttpURLConnection) url.openConnection();
        InputStream in = urlConnection.getInputStream();
        InputStreamReader reader = new InputStreamReader(in);

        int data = reader.read();
        while (data != -1) {
            char current = (char) data;
            result += current;
            data = reader.read();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}

I am facing a problem in understanding, how does result += current statement work.我在理解上遇到了问题, result += current statement 是如何工作的。 Through my understanding, it seems char current data is being transferred to result , but current is an integer that cast into char, and if current is an integer that cast in char transferring to result .根据我的理解,似乎char current数据正在传输到result ,但current是一个转换为 char 的整数,如果current是一个转换为 char 转换为result的整数。 So, how I will be able to extract every line from InputStream as a result prints integer that casted into char not the lines from InputStream.因此,我将如何能够从 InputStream 中提取每一行作为结果打印转换为 char 的整数而不是来自 InputStream 的行。

I know, I am thinking something wrong but I am unable to understand it.我知道,我想错了,但我无法理解。

Please help me to understand how this works :)请帮助我了解这是如何工作的:)

I think you are looking for我想你正在寻找

BufferedReader r = BufferedReader(new InputStreamReader(in));
List<String> lines  = r.readLines();

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

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