Java Reference
In-Depth Information
5 System.out.println(
"File already exists"
);
6 System.exit(
1
);
7 }
8
9
// Create a file
10 java.io.PrintWriter output =
new
java.io.PrintWriter(file);
11
12
// Write formatted output to the file
13 output.print(
"John T Smith "
);
14 output.println(
90
);
15 output.print(
"Eric K Jones "
);
16 output.println(
85
);
17
18
// Close the file
19 output.close();
20 }
21 }
create
PrintWriter
print data
John T Smith 90
Eric K Jones 85
scores.txt
close file
Lines 4-7 check whether the file scores.txt exists. If so, exit the program (line 6).
Invoking the constructor of
PrintWriter
will create a new file if the file does not exist. If
the file already exists, the current content in the file will be discarded without verifying with
the user.
Invoking the constructor of
PrintWriter
may throw an I/O exception. Java forces you to
write the code to deal with this type of exception. For simplicity, we declare
throws
IOException
in the main method header (line 2).
You have used the
System.out.print
,
System.out.println
, and
System.out.printf
methods to write text to the console.
System.out
is a standard
Java object for the console. You can create
PrintWriter
objects for writing text to any file
using
print
,
println
, and
printf
(lines 13-16).
The
close()
method must be used to close the file. If this method is not invoked, the data
may not be saved properly in the file.
create a file
throws IOException
print
method
close file
14.11.2 Reading Data Using
Scanner
The
java.util.Scanner
class was used to read strings and primitive values from the con-
sole in Section 2.3, Reading Input from the Console. A
Scanner
breaks its input into tokens
delimited by whitespace characters. To read from the keyboard, you create a
Scanner
for
System.in
, as follows:
Scanner input =
new
Scanner(System.in);
To read from a file, create a
Scanner
for a file, as follows:
Scanner input =
new
Scanner(
new
File(filename));
Figure 14.9 summarizes frequently used methods in
Scanner
.
Listing 14.14 gives an example that creates an instance of
Scanner
and reads data from
the file
scores.txt
.
L
ISTING
14.14
ReadData.java
1
import
java.util.Scanner;
2
3
public class
ReadData {
4
public static void
main(String[] args)
throws
Exception {
5
// Create a File instance
6 java.io.File file =
new
java.io.File(
"scores.txt"
);
7
8
create a
file
// Create a Scanner for the file