简体   繁体   English

使用 BufferedReader 对效率有何影响?

[英]What are the efficiency implications of using BufferedReader?

What is the difference between these 2 methods used to read characters from a file.这两种用于从文件中读取字符的方法有什么区别。

FIRST第一的

FileReader fr = new FileReader( new File( "file.txt") );
int x = 0;
while( ( x = fr.read() ) != -1 ) {
    System.out.println( (char) x );
}

SECOND第二

BufferedReader bfr = new BufferedReader( new FileReader( new File( "file.txt") ) );
int x = 0;
while( ( x = bfr.read() ) != -1 ) {
    System.out.println( (char) x );
}

Both the codes read the characters from the file and write it on the console.这两个代码都从文件中读取字符并将其写入控制台。

Which one of the method is more efficient and why?哪种方法更有效,为什么? Or it's the same thing?还是一样的?

Consider a water tank 5km away from you.考虑距离您 5 公里的水箱。 For every bucket of water you had to travel 5km.对于每一桶水,您必须行驶 5 公里。 For reducing your effort, you bring a small tank and fill it once for 3-4 days.为了减少你的努力,你带一个小罐子,装满一次 3-4 天。 Then full your buckets from the small water tank, inside your house.然后从你房子里的小水箱里装满你的水桶。

In above example the water tank 5km away is a file on the hard disk, If you use a bare reader, it is like travelling 5km for every bucket of water.在上面的例子中,5公里外的水箱是硬盘上的一个文件,如果你使用裸读器,每桶水就相当于走了5公里。 So you bring a small tank(BufferedReader).所以你带了一个小坦克(BufferedReader)。

Thus spake the docs :因此说文档

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream.通常,由 Reader 发出的每个读取请求都会导致对底层字符或字节 stream 发出相应的读取请求。 It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders.因此,建议将 BufferedReader 包装在 read() 操作可能成本高昂的任何 Reader 周围,例如 FileReaders 和 InputStreamReaders。

Just a little addition to @cwallenpoole's answer.只是对@cwallenpoole 答案的一点补充。 There is also difference in the interface.界面也有区别。 For example, in BufferedReader there is a nice method readLine(), which I use heavily.例如,在 BufferedReader 中有一个很好的方法 readLine(),我大量使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM