What are the implications of using BufferedReader efficiently?

What is the difference between the two 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 codes read characters from a file and write them to the console.

Which method is more effective and why? Or is it the same thing?

+4
source share
3 answers

So enter docs :

In general, each read request made from Reader raises a read request that must be made from a base character or byte stream. Therefore, it is recommended that you wrap the BufferedReader around any Reader whose read () operations can be expensive, such as FileReaders and InputStreamReaders.

+9
source

Consider a water tank 5 km from you. For each bucket of water you had to drive 5 km. To reduce your efforts, you bring a small tank and fill it once for 3-4 days. Then fill your buckets from a small water tank inside your home.

In the above example, a 5 km water tank is a file on your hard drive. If you use a naked reader, it is like traveling 5 km for each bucket of water. This way you bring a small tank (BufferedReader).

+13
source

Just a small addition to @cwallenpoole's answer. There is also a difference in the interface. For example, BufferedReader has a nice readLine () method, which I use heavily.

0
source

All Articles