Use File or FileReader with Scanner?

orbfish picture orbfish · Jan 26, 2012 · Viewed 23k times · Source

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.

Answer

maximdim picture maximdim · Jan 26, 2012

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.