class LogReader {
public void readLogFile(String path){
BufferedReader br = new BufferedReader(new FileReader(path));
String currentLine=null;
while(currentLine=br.readLine()!=null){
System.out.println(currentLine);
}
}
}
Imagine I have a log file worth several 100 Megs. Will the above code load the entire file in memory ? If so what is the real benefit of buffering here ?
I am reading File I/O and not able to grasp the idea of whether we will load the bytes worth a line (currentLine) above in the memory or the whole file gets into memory and then each line gets read and assigned to the variable in memory again.
Please tell me the way I can avoid loading the entire file in memory if this is not the way.
Will the above code load the entire file in memory ?
No.
If so what is the real benefit of buffering here ?
The benefit is in reading data a chunk at a time, which is typically more efficient than reading one character at a time or similar, and buffering it so your interface to the data is still as granular as you want it to be (read
, readLine
, etc.).
Here's an excerpt from the BufferedReader
documentation:
Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.
In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,
BufferedReader in = new BufferedReader(new FileReader("foo.in"));
will buffer the input from the specified file. Without buffering, each invocation of
read()
orreadLine()
could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.
(my emphasis)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With