Thursday 15 April 2010

Should BufferedWriter have open()?

An object of BufferedWriter class has a parameterized constructor which takes an object of FileWriter Class. With this it becomes a handler to the file which FileWriter’s object corresponds to.

This handler has functions like write(), flush() and close(). Initially I was under impression that there must be an open() function too - To open the connection to the same file again. But it is not present.

I wondered - why is it not present? If it can close the connection, it should be able to open it again. But it is not.

Then my question changed to - Why should it be present first of all?
To open the closed file if we need it somewhere after closing it.

And then what is the purpose of closing the connection?
We close it so that the file will be freed to delete, to move or to do anything on it i.e. for the file to get rid of its handler.

What if it was present?
After closing the connection how would it find the file which it has to connect to? And suppose your handler kept the details of file with itself in order to open the same file again. But again in meantime when it was disconnected from the file, if someone moved file to some different location, how would you rely on old information? Or you are making handler to keep following the file until handler is alive? Then how will the file get rid of the handler?

Anyway, to open the already closed file and to append data to it, you have ‘append’ option in the constructor of FileWriter.

No comments: