Java Reference
In-Depth Information
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
create
PrintWriter
print data
John T Smith 90
Eric K Jones 85
scores.txt
close file
}
21 }
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 output. 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 (line 19). 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
12.11.2 Closing Resources Automatically Using try-with-resources
Programmers often forget to close the file. JDK 7 provides the followings new try-with-
resources syntax that automatically closes the files.
try
(declare and create resources) {
Use the resource to process the file;
}
Using the try-with-resources syntax, we rewrite the code in Listing 12.13 in Listing 12.14.
L
ISTING
12.14
WriteDataWithAutoClose.java
1
public class
WriteDataWithAutoClose {
2
public static void
main(String[] args)
throws
Exception {
3 java.io.File file =
new
java.io.File(
"scores.txt"
);
4
if
(file.exists()) {
5 System.out.println(
"File already exists"
);
6 System.exit(
0
);
7 }
8
9
try
(
10
// Create a file
11 java.io.PrintWriter output =
new
java.io.PrintWriter(file);
12 ) {
13
// Write formatted output to the file
14 output.print(
"John T Smith "
);
15 output.println(
90
);
16 output.print(
"Eric K Jones "
);
17 output.println(
85
);
18 }
19 }
20 }
declare/create resource
use the resouce
Search WWH ::
Custom Search