Reputation: 7741
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.
Upvotes: 15
Views: 27625
Reputation: 20792
Horses for courses. From the Scanner javadocs, a Scanner is "A simple text scanner which can parse primitive types and strings using regular expressions." So, my take on your question is: it does not matter which approach you use, the simpler option with File is just as good as the one found in Oracle tutorials. Scanner is for convenient tokenizing of text files, and if your file is small, as you said, than it's a perfect fit.
Because a Scanner uses regular expressions, you can't really expect huge performance with it, whether you create a buffered file reader for the scanner or not. The underlying Readable will be close()d (if it's a Closeable, which it will be, if you use the Scanner(File) constructor), and so you don't have to worry as long as you close() your Scanner object (or use try-with-resources).
Upvotes: 1
Reputation: 159
Yes you can do that.
Basically you do:
Scanner file = new Scanner(new FileReader("file.txt"));
To read a String:
String s = file.next();
When you are done with the file, do
file.close();
Upvotes: 1
Reputation: 62459
The File
class has no close()
method because it only abstracts a disk file. It is not an input stream to the file, so there is nothing to close.
Upvotes: 3
Reputation: 8169
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.
Upvotes: 6
Reputation: 41
There are multiple ways to construct a Scanner object.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
I personally wouldn't even use Scanner for file reading though. Look at BufferedReader tutorials. It's not too hard to figure out.
Upvotes: -4