1

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 :)

Son Truong
  • 13,661
  • 5
  • 32
  • 58

1 Answers1

0

I think you are looking for

BufferedReader r = BufferedReader(new InputStreamReader(in));
List<String> lines  = r.readLines();
Sarah Khan
  • 836
  • 7
  • 11
  • Thank you. But in above question, I am trying to understand the function of that particular code for curiosity. By the way, this code is simple and easily applicable, I would definately use BufferedReader in my project. – Sachin Singh Nov 25 '20 at 03:39