I have been noticing a in new Java textbook editions- the use of Scanner with Text Files. However, there seems to be not a consensus in the books on what classes to use with Scanner with reading text files. Some use the File Class in tandem with Scanner others use FileReader and Scanner together.
Which classes do you Java professionals/users tend to use with text files..Give me a better direction on teaching files
Mr. C<br /> <br />Author and Instructor<br />My book:<br /><a href="http://www.aw-bc.com/catalog/academic/product/0,1144,1576761614,00.html" target="_blank" rel="nofollow">http://www.aw-bc.com/catalog/academic/product/0,1144,1576761614,00.html</a>
Joined: Oct 13, 2005
Have you been through the Scanner class in the API? It is described as a "simple text scanner;" it is simple, but in the circumstances where it works, very effective. You can use it with text files, the standard input stream, etc. In the API there are several constructors, some taking a File object, but I couldn't find one with a FileReader as a parameter.
Many people now use Scanners for keyboard input rather than BufferedReaders and StreamReaders.
It is only available in J2SE5.0 and later.
And it has an opposite: Formatter. [ July 19, 2006: Message edited by: Campbell Ritchie ]
Joined: Jan 30, 2000
[CR]: but I couldn't find one with a FileReader as a parameter.
public Scanner(Readable source)
All Readers now retroactively implement Readable, so this constructor will accept a FileReader. If you've already got a FileReader for some reason, you might as well use this constructor I suppose. But in general I see no benefit to creating a FileReader just to pass it to a Scanner; I would rather just use one of the consrtuctors that takes a File. Also note that with a FileReader there's no way to specify a particular encoding. Until now you needed to construct an InputStreamReader wrapped around a FileInputStream, if you wanted a particular encoding. Now Scanner allows you to directly specify encoding along with a File - much simpler.
Many programmers will overlook the possibility that they need to specify an encoding other than the default, but at least Scanner makes it easy to do, if and when the need is discovered. FileReader was originally a convenience class for reading text from files; with Scanner we have a more powerful convenience class for the same thing. I would pretty much forget about FileReader in code for 1.5+. Scanners are the way to go. [ July 19, 2006: Message edited by: Jim Yingst ]
"I'm not back." - Bill Harding, Twister
Joined: Oct 06, 2002
Jim answered my question CR.
I know what Scanner is and have taught Scanner for files/console I/O for two semesters now..Just asking for opinion- since it is not consistent in Java Programming texts (1.5)
Oh and it is Malik that uses this:
Scanner inFile = new Scanner(new FileReader(filename));
Others use the File Class... JC
Joined: Jan 24, 2006
if you have a file you want to read from, you can do the following?