Java Reference
In-Depth Information
37 input.close();
38 output.close();
39 }
40 }
close file
In a normal situation, the program is terminated after a file is copied. The program is termi-
nated abnormally if the command-line arguments are not used properly (lines 7-11), if the
source file does not exist (lines 14-18), or if the target file already exists (lines 22-25). The
exit status code 1, 2, and 3 are used to indicate these abnormal terminations (lines 10, 17, 24).
14.29
How do you create a
PrintWriter
to write data to a file? What is the reason to
declare
throws Exception
in the main method in Listing 14.13, WriteData.java?
What would happen if the
close()
method were not invoked in Listing 14.13?
14.30
Show the contents of the file
temp.txt
after the following program is executed.
✓
✓
Check
Point
public class
Test {
public static void
main(String[] args)
throws
Exception {
java.io.PrintWriter output =
new
java.io.PrintWriter(
"temp.txt"
);
output.printf(
"amount is %f %e\r\n"
,
32.32
,
32.32
);
output.printf(
"amount is %5.4f %5.4e\r\n"
,
32.32
,
32.32
);
output.printf(
"%6b\r\n"
, (
1
>
2
));
output.printf(
"%6s\r\n"
,
"Java"
);
output.close();
}
}
14.31
How do you create a
Scanner
to read data from a file? What is the reason to define
throws Exception
in the main method in Listing 14.14, ReadData.java? What
would happen if the
close()
method were not invoked in Listing 14.14?
14.32
What will happen if you attempt to create a
Scanner
for a nonexistent file? What
will happen if you attempt to create a
PrintWriter
for an existing file?
14.33
Is the line separator the same on all platforms? What is the line separator on Windows?
14.34
Suppose you enter
45 57.8 789
, then press the
Enter
key. Show the contents of the
variables after the following code is executed.
Scanner input =
new
Scanner(System.in);
int
intValue = input.nextInt();
double
doubleValue = input.nextDouble();
String line = input.nextLine();
14.35
Suppose you enter
45
, press the
Enter
key,
57.8
, press the
Enter
key,
789
, and press
the
Enter
key. Show the contents of the variables after the following code is executed.
Scanner input =
new
Scanner(System.in);
int
intValue = input.nextInt();
double
doubleValue = input.nextDouble();
String line = input.nextLine();
JFileChooser
is a GUI component for displaying a file dialog.
Java provides the
javax.swing.JFileChooser
class for displaying a file dialog, as shown
in Figure 14.10. From this dialog box, the user can choose a file.
Key
Point