BufferedReader中的缓冲区大小是多少? [英] What is the buffer size in BufferedReader?
问题描述
构造函数中缓冲区大小的含义是什么?
What is the sense of buffer size in the constructor?
BufferedReader(Reader in, int size)
我已经编写了程序:
import java.io.*;
class bufferedReaderEx{
public static void main(String args[]){
InputStreamReader isr = null;
BufferedReader br = null;
try{
isr = new InputStreamReader(System.in);
// System.out.println("Write data: ");
// int i = isr.read();
// System.out.println("Data read is: " + i);
//Thus the InputStreamReader is useful for reading the character from the stream
System.out.println("Enter the data to be read by the bufferedReader: ");
//here isr is containing the lnefeed already so this is needed to be flushed.
br = new BufferedReader(isr, 2);
String str = br.readLine();
System.out.println("The data is : :" + str);
}catch(IOException e){
System.out.println("Can't read: " + e.getMessage());
}
}
}
输出:
Enter the data to be read by the bufferedReader: Hello world and hello world again
The data is: Hello world and hello world again
然后,缓冲区大小是什么意思,因为我打算只读取两个字符.但是不是那样.
Then what does the buffer size means as i intended that it would be reading only two characters. but it was not that.
推荐答案
BufferedReader
缓冲输入.这意味着它将在传递给您之前从输入源读入缓冲区.这里的缓冲区大小是指它缓冲的字节数.
BufferedReader
buffers the input, just as the name says. This means that it reads from the input source into a buffer before passing it onto you. The buffer size here refers to the number of bytes it buffers.
从大多数来源读取输入内容的速度非常慢.仅2个字节的缓冲区将损害性能,因为您的程序很可能大部分时间都在等待输入.缓冲区大小为2时,读取100字节将导致从内存缓冲区中读取2个字节(非常快),填充缓冲区(非常慢),从缓冲区中读取2个字节(非常快),填充内存.缓冲区(非常慢),等等-整体非常慢.缓冲区大小为100时,读取100个字节将导致从内存中的缓冲区中读取100个字节(非常快)-总体而言非常快.假设在读取时缓冲区包含100个字节,在您这样的情况下,这是一个合理的假设.
Reading input from most sources is very slow. A buffer of just 2 bytes is going to hurt performance, as your program is very likely going to be waiting on input most of the time. With a buffer size of 2, a read of 100 bytes will result in reading 2 bytes from the in-memory buffer (very fast), filling the buffer (very slow), reading 2 bytes from the buffer (very fast), filling the buffer (very slow), etc - overall very slow. With a buffer size of 100, a read of 100 bytes will result in reading 100 bytes from the in-memory buffer (very fast) - overall very fast. This is assuming the buffer is contains the 100 bytes when reading though, which in a case like yours is a reasonable assumption to make.
除非您知道自己在做什么,否则应使用很大的默认缓冲区大小.使用较小的缓冲区的原因之一是当您在内存有限的设备上运行时,因为缓冲区占用了内存.
Unless you know what you're doing, you should use the default buffer size which is quite large. One reason for a smaller buffer is when you are running on a limited-memory device, as the buffer consumes memory.
这篇关于BufferedReader中的缓冲区大小是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!