Reputation: 21319
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 ?
Upvotes: 5
Views: 1399
Reputation:
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).
Upvotes: 15
Reputation: 8282
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.
Upvotes: 0
Reputation: 81988
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.
Upvotes: 9