Reputation: 11944
BufferedReader buf2=new BufferedReader(
new InputStreamReader(new FileInputStream("D:/info.txt")));
Out of these two methods for reading the contents of a file which method is better and why?
BufferedReader buf=new BufferedReader(new FileReader("D:/info.txt"));
Upvotes: 0
Views: 210
Reputation: 13872
From java docs:
FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream.
So, it depends on your requirements.
For more clarity keep reading:
FileReader can't handle network connections streams, etc.
FileReader doesn't care of encoding but uses the plaform default encoding, and hence limits platform independence.
Thus, forget FileReader
(most of the times).
Upvotes: 1
Reputation: 206796
Both lines are equivalent; in both cases you'll get a BufferedReader
which will allow you to read text from the file.
A possible advantage of the first approach is that you can change it slightly to specify the character encoding that you want to use for reading the file, for example:
BufferedReader buf2 = new BufferedReader(new InputStreamReader(
new FileInputStream("D:/info.txt"), "UTF-8"));
FileReader
does not allow you to specify the character encoding and will always use the default character encoding of your platform, which is not always what you want.
Upvotes: 3
Reputation: 346260
If used as is, both have exactly the same effect. However, using InputStreamReader
allows you to specify the text encoding as second parameter to the constructor, and you should nearly always do that because There Ain't No Such Thing as Plain Text.
Upvotes: 2
Reputation: 10747
Readers are for text I/O, while Streams are for binary I/O . You have to take care of Encoding/Decoding issue while using Reader which could be avoided with InputStream.
Take a look at FileInputStream vs FileReader for details.
Upvotes: 1