I'm really confused. I've seen a lot of implementations on how to read a file in Java, and the more I read, the less it makes sense to me.
As I noticed, the preferred way to read a file is to use BufferedReader
over Scanner
.
But, I've seen examples like:
Scanner s = new Scanner(new BufferedReader(...);
Instead of just:
Scanner s = new Scanner(new File("foo.txt"));
What would be the reason to initialize a Scanner
with BufferedReader
?
Are there any advantages to do it this way?
Now, what I find more confusing is, everywhere I looked, there are suggestions for using Path
Object instead of File
.
But, I found no elegant way of initializing BufferedReader
with Path
Objects, as both BufferedReader
& FileReader
cannot accept Path
.
There is of course a way to just do something like:
Path path = Paths.get("foo.txt");
BufferedReader br = new BufferedReader(new FileReader(path.toFile()));
But that looks like a lot of mess.
My questions regarding BufferedReader
are:
- Should I even use
BufferedReader
? - What's the purpose of
FileReader
? Why Can't I just initializeBufferedReader
with aString
orPath
?