使用 BufferedReader 对效率有何影响?
这两种用于从文件中读取字符的方法有什么区别?
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 );
}
两个代码都从文件中读取字符并将其写入控制台。
哪一种方法更有效?为什么? 或者是同一件事?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
考虑一个距离您 5 公里的水箱。每喝一桶水,您就需要行驶 5 公里。为了省力,你可以带一个小水箱,3-4天加满一次。然后用屋内的小水箱装满水桶。
在上面的例子中,5公里外的水箱是硬盘上的一个文件,如果使用裸读卡器,每桶水相当于行驶了5公里。所以你带了一个小坦克(BufferedReader)。
Consider a water tank 5km away from you. For every bucket of water you had to travel 5km. For reducing your effort, you bring a small tank and fill it once for 3-4 days. 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. So you bring a small tank(BufferedReader).
文档如此说道:
Thus spake the docs:
只是对@cwallenpoole 的答案进行一点补充。接口上也有区别。例如,在 BufferedReader 中,有一个很好的方法 readLine(),我经常使用它。
Just a little addition to @cwallenpoole's answer. There is also difference in the interface. For example, in BufferedReader there is a nice method readLine(), which I use heavily.