Java Reference
In-Depth Information
2.3
Introduction to File Input
You shall see them on a beautiful quarto page, where a neat rivulet of text shall
meander through a meadow of margin.
RICHARD BRINSLEY SHERIDAN, The School for Scandal
The Scanner class can also be used to read data from a text file. To do this, we must
create a Scanner object and link it to the file on the disk. Once this is done, the
program can read from the Scanner object in the same exact way that we read from the
console, except the input will come from the file instead of typed from the keyboard.
Details about reading and writing from files are not discussed until Chapter 10 and
require an understanding of programming concepts we have not yet covered. However,
we can provide just enough here so that your programs can read from text files. This
will allow you to work on problems with real-world data that would otherwise be too
much work to type into your program every time it is run.
The Scanner Class for Text File Input
To read from a text file, we need to import the classes FileInputStream and
FileNotFoundException in addition to the Scanner class:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
The FileInputStream class handles the connection between a Java program and a
file on the disk. The FileNotFoundException class is used if a program attempts to
open a file that doesn't exist.
To open the file, we create an object of type Scanner and then connect it with
a FileInputStream object associated with the file. We have to handle the scenario
where we try to open a file that doesn't exist. One way to do this is with a try/catch
block. This is discussed more thoroughly in Chapter 9, but the basic format to open a
file looks like this:
Scanner fileIn = null ; // initializes fileIn to empty
try
{
// Attempt to open the file
fileIn = new Scanner( new FileInputStream("PathToFile"));
}
catch (FileNotFoundException e)
{
// If the file could not be found, this code is executed
// and then the program exits
 
 
Search WWH ::




Custom Search