Java BufferedReader value become null

ぐ巨炮叔叔 提交于 2019-12-02 16:57:43

问题


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

BufferedReader bf = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        System.out.println("bf.readLine() - " + bf.readLine());

        output = bf.readLine();
        while (output != null) {
            JSONObject obj = new JSONObject(output);
            System.out.println("output is " + output);
            resCode = obj.getString("resCode");
            resDesc = obj.getString("COUNT");
        }

I can return bf.readLine() response as follows.

{"status":true,"data":[{"COUNT":"0"}]}

Problem is when I assign the bf.readLine() to String and check the value, it becomes null. Why bf.readLine() shows as null (gives null point exception) even it return the value from API.


回答1:


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");
        }



回答2:


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



来源:https://stackoverflow.com/questions/37850691/java-bufferedreader-value-become-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!