0

   BufferedReader br = new BufferedReader(new FileReader(fileLocation));
   String contentLine = br.readLine();
   while(contentLine!= null){
     System.out.println(contentLine);
     contentLine = br.readLine();

   }

   return contentLine; // returns null
 }

Hello All, I am in process of learning java, and here i am trying to parse a file that prints out the json message, the challenge I am facing is, I need to return that json which is inside while loop. Currently, the method returns null

6
  • I tried add the line of code return contentLine += br.readLine(); I throws an error at "+" saying expression expected Commented Nov 25, 2021 at 7:03
  • 1
    In your loop change contentLine = br.readLine(); to contentLine += br.readLine(); Commented Nov 25, 2021 at 7:04
  • 3
    @ScaryWombat if you do that, you'll never get out of the loop, though Commented Nov 25, 2021 at 7:07
  • @Stultuske true, i just tried that and its not coming out of loop. Commented Nov 25, 2021 at 7:08
  • 2
    @Peter keep your code as is, and store the data to return in a different variable Commented Nov 25, 2021 at 7:08

1 Answer 1

1

To cement the comments above, use a different variable and then append to the returned value

BufferedReader br = new BufferedReader(new FileReader(fileLocation));

StringBuilder contentLine = new StringBuilder ();
while(true){
     String tmp = br.readLine();
     if (tmp == NULL) {
         break;
     }
     contentLine.append (tmp);
     System.out.println(contentLine.toString ());
}

return contentLine.toString ();
Sign up to request clarification or add additional context in comments.

3 Comments

This worked, but the way its appending and completes the json is like this in console. { "page": { { "page": { "size": 2, { "page": { "size": 2, "number": 2, { "page": { "size": 2, "number": 2, "numberOfPages": 1,
you can always add a breakline each time you do .append(tmp);
@user16320675 - Absolutely agree, but just keeping with the original code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.