Buffered reader does not flush characters to buffer when reaching EOF

I have a buffered reader using read(buffer, off, len). The reader is reading a txt file into a buffer of 2048 characters. It reads and prints whats in the buffer fine until it reaches the end and returns -1. At that point it not longer flushes the last characters into its buffer.

Ive tried reseting the buffer after each read to no avail.

Code to reproduce.

When running the code, the last time it reads it must not completely fill the buffer.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

```
public class bufferRead{
    public static void main(String[] args) {
       
        try {
            FileReader reader = new FileReader("path to file");
            BufferedReader br = new BufferedReader(reader);

            char[] buffer = new char[2048];
            int off = 0;
            int totalNumRead = 0;
            int numRead;
            while ((numRead = br.read(buffer, off, 2048)) != -1) {
                totalNumRead += numRead;
                System.out.println(numRead + " " + totalNumRead);
                System.out.println(buffer);
            }
            System.out.println(buffer);
            System.out.println(numRead + " " + totalNumRead);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
} 

>Solution :

Note that br.read(buffer, off, 2048) returns the number of characters read in.

For the very last iteration of the loop, numRead might be less than buffer.length so buffer will contain characters from last AND second last row:

 System.out.println(buffer);

But if you change to this, it will only print what was read in for each iteration as it sets the printed value to the exact number of characters read in:

 System.out.println(new String(buffer,0, numRead));

Leave a Reply