PDA

View Full Version : Reading with BufferedReader



Trinithis
09-12-2007, 07:53 AM
I was reading about the BufferedReader class and looked at its read methods.

I noticed it overrides one of the two (non-abstract) read methods, read(char[] cbuf, int off, int len), but not read(char[] cbuf).

Because it does not override read(char[] cbuf), it makes me wonder if for reading an entire file into a char[] array more efficient than using read(char[] cbuf, int off, int len).

Which is better?

Or better yet, is there a better way of doing this:


//try catch finally excluded for simplicity

File f = new File("abc.def");
char[] cbuf = new char[(int)f.length()]; //assuming the file is small enough
BufferedReader br = new BufferedReader(new FileReader(f));
br.read(cbuf);
//or br.read(cbuf, 0, (int)f.length()); ???
br.close();

Twey
09-12-2007, 08:11 AM
That's really not what BufferedReader is for. As the name implies, it's designed to simplify the process of reading a small amount of data (usually a line) into a buffer for processing. Using it for reading the whole file into a char[] is at best superfluous and at worst detrimental to performance -- I would suspect that the overwritten read() exists to help keep track of the buffer and make sure that read()s don't interfere with the internal buffer more than they ought. Either way, it will almost certainly store more data than is necessary for such an operation.