I missed that - maybe my brain needs a spring clean since I didn't
manage to deduce that one from the Javadocs. The reasoning behind
keeping BufferedReader separate from FileReader is fine - until you want
to read lines! IMO there's a reasonable case to be made that readLine()
should be a FileReader method instead of something that can only be done
through a BufferedReader. To generalize the point, using the buffered
wrapper should purely add buffering without changing the set of data
access methods.
The problem is that it's traditionally considered impossible to implement
readLine without a buffer. At least, if you want to be able to handle
multiple forms of line ending - CR, LF and CRLF. Why? Well, what do you do
when you hit a CR? Declare the line finished, and return it? What if the
next character's a LF? Then the line terminator is actually CRLF, and your
next read will give you a spurious empty line when it hits the LF. What
you have to do is read the CR, then read the next character, and if it's
an LF, carry on, but if it's not, unread it - put it back into the input.
You can't do that without a buffer, although it does only need to be one
character big. That's part of the reason why PushbackInputStream exists -
DataInputStream uses it internally to implemented ReadLine. Aah, JDK 1.0.
Now, i'm not actually sure that the above argument is true. I've never
stopped to question it before, but couldn't you just have a flag in the
reader, a boolean lastLineReadEndedWithCR, and the next time you read a
character, if it's set, you check to see if the character is an LF, and if
it is, throw it away. Would that work? It would involve doing a test every
single time you read a character, though, which could be inefficient, and
it's not immediately obvious how it would work with read(char[]), although
my gut feeling is that wouldn't be complicated. I think you might also
have trouble with available() and semantics with regard to the position in
the file.
Since buffering is almost always a good idea, though, shouldn't you almost
always be using a buffer? And if so, does it matter that FileReader
doesn't have readLine?
tom