-1

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?

  • The variable ``i`` tells you how many characters have been read into your buffer. But you still print the whole array, not only the data from ``text[0]`` to ``text[i-1]``. – f1sh Jan 06 '17 at 15:32
  • Use `ArrayList` or some other Collection. – PM 77-1 Jan 06 '17 at 15:32
  • http://stackoverflow.com/questions/19108624/confusion-on-readchar-cbuf-int-off-int-len-from-class-reader – Sotirios Delimanolis Jan 06 '17 at 18:05
  • What’s the point of `bufferIn = new BufferedReader(inStreamBooks);` when you are using the original `FileReader` afterwards? Note that if you would use the `BufferedReader` you’ve created, you could use its `readLine()` method which simplifies your task a lot… – Holger Jan 06 '17 at 19:22

3 Answers3

0

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

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

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));
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

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.