dmaprasad dmaprasad - 1 year ago 88
Java Question

Java BufferedReader value become null

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

BufferedReader bf = new BufferedReader(new InputStreamReader(
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.


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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download