Java Reference
In-Depth Information
Scanner inFile = new Scanner( new FileReader("prog.dat"));
//Line 1
Next, you use the object inFile to input the data from the file prog.dat , just the way
you used the object console to input the data from the standard input device using the
methods next , nextInt , nextDouble , and so on.
The statement in Line 1 assumes that the file prog.dat is in the same directory
(subdirectory) as your program. However, if this is in a different directory (subdirectory),
then you must specify the path where the file is located, along with the name of the file.
For example, suppose that the file prog.dat is on a flash memory in drive H. Then, the
statement in Line 1 should be modified as follows:
Scanner inFile = new Scanner( new FileReader("h:\\prog.dat"));
Note that there are two \ after h: . Recall from Chapter 2 that in Java \ is the escape
character. Therefore, to produce a \ within a string you need \\ . (Moreover, to be
absolutely sure about specifying the source where the input file is stored, such as the
flash drive h:\\ , check your system's documentation.)
Suppose that a program reads data from a file. Because different computers have
drives labeled differently, for simplicity, throughout the topic we assume that the file
containing the data and the program reading data from the file are in the same directory
(subdirectory).
To send the output to a file, you use the class PrintWriter . This class is contained in
the package java.io .
To summarize, Java file I/O is a four-step process:
1. Import the necessary classes from the package s java.util and java.io
into the program.
2. Create and associate the appropriate objects with the input/output
sources.
3. Use the appropriate methods associated with the variables created in
Step 2 to input/output the data.
4. Close the files.
We now explain these four steps and then provide a skeleton program that shows how
the steps might appear in a program.
Step 1 requires that the necessary classes be imported from the package s java.util and
java.io . The following statements accomplish this task:
 
Search WWH ::




Custom Search