8

I'm writing a small application in java

I read text files in various sizes and I need to read them line by line (and insert the line into array).
Is there difference between BufferedReader.ReadLine() and RandomAccessFile.ReadLine(), in terms of performance?

Is there any reason to prefer one or the other?

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
choppy
  • 739
  • 1
  • 12
  • 22

1 Answers1

6

RandomAccessFile.readLine() might be slightly faster because it ignores character encoding. However it doesn't use buffering and still use StringBuffer :P so it could be slower on your system.

BufferedReader.readLine() is preferred because it handles character encoding e.g. UTF-8 or Windows-1252.

There is also a DataInputStream.readLine() which can be used with BufferedInputStream. Only use this is you can be sure you want ISO-8859-1 or ASCII encoding.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • What about buffer usage, somebody wrote that BufferedReader might be faster because it uses buffer and RandomAccessFile not, is it true? – choppy May 01 '12 at 17:28
  • Good point, I may have been confused with DataInputStream + BufferedInputStream. – Peter Lawrey May 01 '12 at 19:12
  • 1
    @choppy Yes, that's true. BufferedReader reads characters from the specified stream and stores them in a buffer. This increases the rate at which input is read. – CaitlinG Jun 20 '19 at 20:19