1

I have a dubt about to class BufferedReader. This my test. I create the simple txt file: "test.txt" with 1024 lines. Each line contains the line number and the file name (example: "1 - test.txt"):

Test file creation:

$ for i in {0..1023}; do echo "$i - test.txt" >> test.txt; done
$ ls -la test.txt
-rw-r--r--    1 osb      osb           12288 Oct 26 12:01 test.txt

The Java class for my test (f is a variable of File class):

...
while (f.exists())
    {
        BufferedReader br = null;

        try
        {

            br = new BufferedReader( new FileReader( f ), 10);

            while ((line = br.readLine())!=null)
            {
                System.out.println (line);
                Thread.sleep(1000);
            }

        }

        ...
        catch excepion
        ...

        finally
        {
            try
            {
                br.close();
            }
            catch (IOException e)
            {
                System.out.println ("\nError closing Buffer reader!");
                e.printStackTrace();
            }
            br = null;
            line = null;
        }

    }
...

When the application starts to write the lines I execute this unix command:

gzip test.txt

I expect an exception because the buffer size is very little ( 10 byte ) less than un line size, but the application reads all the 1024 lines and only when it reaches the end of the file it raises the exception ( file not exist! ). Does the BufferedReader has a buffersize greater than 10? Is there a minimum buffer size?

Thanks

1 Answer 1

1

Your problem is basically that your assumptions do not at all match up reality.

You think that your Java code directly interacts "with that file" somewhere on some drive.

But in reality, you have several layers between "your java code" and the "thing" out there. First and foremost: the Linux kernel. Even when you are using a BufferedReader, it is very much likely that the Linux kernel might have read the complete content of your little text file as soon as your program starts running. Thus your "reading" code doesn't notice at all that the underlying file was renamed in the meantime!

Just in the very end, when you close the buffer, the JVM notices that things are askew.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks GhostCat for your quick reply, I understand the scenario

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.