Java BufferedReader value become null

后端 未结 2 878
谎友^
谎友^ 2021-01-26 08:15

I\'m using following code to get response from the API.

BufferedReader bf = new BufferedReader(new InputStreamReader(
                connection.getInputStream(         


        
相关标签:
2条回答
  • 2021-01-26 08:48

    Your code should be

    BufferedReader bf = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
    
    String output = null;
    
            while ((output = bf.readLine()) != null) {
             System.out.println("bf.readLine() value is--- - " + output );
    
                JSONObject obj = new JSONObject(output);
                System.out.println("output is " + output);
                resCode = obj.getString("resCode");
                resDesc = obj.getString("COUNT");
            }
    
    0 讨论(0)
  • 2021-01-26 09:04

    The reason is you are calling readLine twice. You calling first at System.out.println("bf.readLine() - " + bf.readLine()); and again at output = bf.readLine();

    Modify as output = bf.readLine();System.out.println("bf.readLine() - " + output);

    As per oracle docsreadLine()

    Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

    if the end of the stream is reached then you will get null and operations on null will give nullpointerexception

    0 讨论(0)
提交回复
热议问题