Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use File or FileReader with Scanner?

Disclaimer: I've looked through all the questions I can find and none of them answers this exact question. If you find one please point me to it and be polite.

So, the Oracle I/O tutorial opens a text file with Scanner as follows:

new Scanner(BufferedReader(FileReader("xanadu.txt")));

But the Javadoc opens a text file with Scanner like this:

new Scanner(new File("myNumbers"));

It would be nice to use the simpler method, especially when I have a small file and can live with the smaller buffer, but I've also seen people say that when you open a File directly you can't close it. If that's the case, why is that idiom used in the official documentation?

Edit: I've also seen new Scanner(FileReader("blah.txt")); but this seems like the worst of both worlds.

Edit: I'm not trying to start a debate about whether to use Scanner or not. I have a question about how to use Scanner. Thank you.

like image 390
orbfish Avatar asked Jan 26 '12 16:01

orbfish


1 Answers

You could look at implementation of Scanner (JDK is shipped with source code). There is a close() method in Scanner class as well. Essentially both approaches you listed are identical for your use case of reading small file - just don't forget to call close() at the end.

like image 59
maximdim Avatar answered Sep 20 '22 13:09

maximdim