How to read whole file with read(char[] cbuf, int off, int len)

754 Views Asked by At

I've got this soure:

public static void inBufferBooks() throws IOException
{
    Reader inStreamBooks = null;
    BufferedReader bufferIn = null;

    try
    {
        inStreamBooks = new FileReader("Files/BufferBook.txt");
        bufferIn = new BufferedReader(inStreamBooks);

        char text[] = new char[10];

        int i = -1;

        while ((i = inStreamBooks.read(text, 0, 10)) != -1)
        {
            System.out.print(text);
        }

When I read file at the end of the text console printing chars who's fill last array. How can I read whole text from the file without redundant chars from last array?

3

There are 3 best solutions below

0
On

How can I read whole text from the file without redundant chars from last array?

Use the value read returns to you to determine how many characters in the array are still valid. From the documentation:

Returns:

The number of characters read, or -1 if the end of the stream has been reached

0
On

You need to remember how may characters you read and only print that many.

for (int len; ((len = inStreamBooks.read(text, 0, text.length)) != -1; ) {
    System.out.print(new String(text, 0, len));
}
0
On

To resolve the problem I change my while cycle like this:

while((i = bufferText.read(text, 0, text.length)) != -1){
            if(text.length == i){
                System.out.print(text);
            }else if (text.length != i){
                    System.out.print(Arrays.copyOfRange(text, 0, i));
            }

Thanks everyone for the help.