11.3 Reading Text Files Using Scanner

Java supports two file types, text and binary. In text files, data is stored as characters; in binary files, data is stored as raw bytes. Different classes are used for writing and reading each file type. The type of a file is determined when the file is written and depends on which classes were used to write to the file. Thus, to read from an existing file, we must know the file’s type in order to select the appropriate classes.

In this section, we concentrate on text files.

As we have seen from Example 11.1, the Scanner class can be used to read from a text file. If the file is not found, the Scanner constructor throws a FileNotFoundException. More exceptions can be thrown by Scanner methods while reading ...

Get Java Illuminated, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.