使用 BufferedReader 对效率有何影响?

发布于 2024-11-29 04:02:59 字数 545 浏览 2 评论 0原文

这两种用于从文件中读取字符的方法有什么区别?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

回首观望 2024-12-06 04:02:59

考虑一个距离您 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).

微凉 2024-12-06 04:02:59

文档如此说道:

一般来说,Reader 发出的每个读取请求都会导致对底层字符或字节流发出相应的读取请求。因此,建议将 BufferedReader 包装在任何 read() 操作可能成本高昂的 Reader 周围,例如 FileReaders 和 InputStreamReaders。

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. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders.

べ映画 2024-12-06 04:02:59

只是对@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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文