java - BufferedReader 读取的字节数

标签 java

据我所知,缓冲读取器比非缓冲读取器进行了优化,因为每次读取都将从内存中完成,无需每次从磁盘/网络进行 I/O 读取/写入。

所以我在这里阅读答案:

Specific difference between bufferedreader and filereader

我对似乎得票很高的第二个答案感到困惑:

When the "read" instruction is given to the BufferedReader object, it uses the FileReader object to read the data from the file. When an instruction is given, the FileReader object reads 2 (or 4) bytes at a time and returns the data to the BufferedReader and the reader keeps doing that until it hits '\n' or '\r\n' (The end of the line symbol). Once a line is buffered, the reader waits patiently, until the instruction to buffer the next line is given.

这是正确的吗?我认为我们失去了关于缓冲区读取器的整个想法,如果缓冲区需要执行多个 2 字节读取,那么我可以只使用文件读取器,也可以使用它。缓冲读取器的想法是一次读取大块,因此 I/O 访问次数将比文件读取器少得多。

如果我错了,有人可以纠正我吗?

最佳答案

看看 BufferedReader javadoc:

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. Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.

因此它预先缓冲来自底层资源的数据,随后的读取指令使用该缓冲区来提高效率。

关于java - BufferedReader 读取的字节数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53985800/

相关文章:

java - 使用android恢复TextView的文本:freezestext not working

Java Spring Controller 处理一个荒谬的 url

static - 使用 PowerMock 的模拟静态 : mock java. lang

java - Android Studio Webview 检查 URL

java - Gradle已将Serenity库加载到项目库,但无法再看到它们

java - 发现未知的扩展标签 : Eclipse Plugin Development

java - Spring聚合框架: How to create nested $divide, $subtract,$mod查询?

java - jmeter加载运行后如何编辑summary.csv文件

java - 如何从点创建多边形 (Spatial4j)

java - 如何从ArrayList的开头删除0