构造函数中缓冲区大小是什么意思?
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
那么缓冲区大小意味着什么,因为我打算它只会读取两个字符。但事实并非如此。
最佳答案
BufferedReader
缓冲输入,正如名字所说。这意味着它在将输入源传递给您之前将其从输入源读取到缓冲区中。这里的缓冲区大小是指它缓冲的字节数。
从大多数来源读取输入非常慢。只有 2 个字节的缓冲区会影响性能,因为您的程序很可能大部分时间都在等待输入。缓冲区大小为 2,读取 100 字节将导致从内存缓冲区读取 2 个字节(非常快),填充缓冲区(非常慢),从缓冲区读取 2 个字节(非常快),填充缓冲区(非常慢)等 - 总体非常慢。缓冲区大小为 100 时,读取 100 字节将导致从内存缓冲区中读取 100 字节(非常快) - 总体速度非常快。这是假设缓冲区在读取时包含 100 个字节,在像您这样的情况下,这是一个合理的假设。
除非您知道自己在做什么,否则您应该使用相当大的默认缓冲区大小。缓冲区较小的一个原因是当您在内存有限的设备上运行时,因为缓冲区会消耗内存。
关于java - BufferedReader 中的缓冲区大小是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4638974/