gpt4 book ai didi

java - BufferedReader 会将整个文件加载到内存中吗?

转载 作者:搜寻专家 更新时间:2023-10-31 20:08:53 24 4
gpt4 key购买 nike

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);
}
}
}

假设我有一个值(value)数百兆的日志文件。上面的代码会将整个文件加载到内存中吗?如果是的话,在这里缓冲的真正好处是什么?

我正在阅读文件 I/O,但无法理解我们是将上面一行 (currentLine) 的字节加载到内存中,还是整个文件进入内存,然后读取每一行并将其分配给内存中的变量再次。

如果不是这种方式,请告诉我如何避免将整个文件加载到内存中。

最佳答案

Will the above code load the entire file in memory ?

没有。

If so what is the real benefit of buffering here ?

好处是一次读取一个 block 的数据,这通常比一次读取一个字符或类似的方式更有效,并对它进行缓冲,以便您的数据接口(interface)仍然像您希望的那样精细( readreadLine 等)。

以下是 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() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.

(我的重点)

关于java - BufferedReader 会将整个文件加载到内存中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45444989/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com