javaandroidinputstreaminputstreamreader

Fetching data from InputStream in java


I am trying to fetch data from InputStream using InputStreamReader and my code is given below.

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. 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. 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.

I know, I am thinking something wrong but I am unable to understand it.

Please help me to understand how this works :)


Solution

  • I think you are looking for

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