BufferedReader会将整个文件加载到内存中吗? [英] Will BufferedReader load the entire file into memory?

查看:1090
本文介绍了BufferedReader会将整个文件加载到内存中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

想象一下我有一个日志文件值几百Megs。上面的代码会将整个文件加载到内存中吗?如果是这样,缓冲的真正好处是什么?

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 / O并且无法理解我们是否会在内存或整个文件中加载上面一行(currentLine)的字节进入内存,然后每行读取并再次分配给内存中的变量。

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 ?

否。


如果是这样,缓冲的真正好处是什么?

If so what is the real benefit of buffering here ?

通过一次读取数据块,这通常比一次读取一个字符更有效,并缓冲它以使您的数据接口仍然像您希望的那样精细是( readLine 等)。

By reading data a chunk at a time, which is typically more efficient than reading one character at a time, and buffering it so your interface to the data is still as granular as you want it to be (read, readLine, etc.).

BufferedReader 文档非常清楚它的作用和原因:

The BufferedReader documentation is quite clear about what it does, and why:


从字符输入流中读取文本,缓冲字符,以提供效率读取字符,数组和行。
可以指定缓冲区大小,也可以使用默认大小。默认值足够大,可用于大多数用途。

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.

通常,由Reader构成的每个读取请求都会导致相应的读取请求由基础字符或字节流构成。因此,建议将BufferedReader包装在任何read()操作可能代价高昂的Reader上,例如FileReaders和InputStreamReaders。例如,

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

将缓冲指定文件的输入。 没有缓冲,每次调用 read() readLine()都可能导致从文件,转换成字符,然后返回,效率非常低。

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.

(我的重点)

这篇关于BufferedReader会将整个文件加载到内存中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆