Does readLine()
Java function used with BufferedReader
cause one disk I/O per call?
If yes, is there any way to read specific number of lines, say n, from a text file causing only one disk I/O?
Here’s the code:
String file;
BufferedReader br = new BufferedReader (new FileReader (file));
int n = 10;
for (int i = 0; i < n; i++)
{
String line = br.readLine ();
/* Do something */
}
3
It depends on how big your lines are.
By default, BufferedReader
uses an 8k buffer (see source). This means that it will attempt to read 8K at a time from the Reader
that it was constructed around. You can read as many lines as will fit into that 8K buffer, without going back to the underlying Reader
.
Edit: As a general comment, do not use FileReader
. Instead, wrap FileInputStream
with an InputStreamReader
, and specify your encoding.
5
You are going through several layers of abstraction between the java code and the disk. There is the Java Virtual Machine and its specific implementation, and then there is the operating system that the JVM is running on, which is then communicating to the disk through some method (it may be a network disk, it may be a local raid, it may be a solid state drive, it may be a stream from a network).
The specifics of the disk IO are determined by the virtual machine and operating system and the underlying source of the data. It may be different for different vm’s in how they ask for io requests – there is no way to determine this from within Java, nor is there a way to communicate at that level with the disk through Java.
3
No. A BufferedReader
stores data in its internal buffer, that’s the entire point of the class. If there’s enough data in there already, a call to readLine()
will not issue another I/O request.