Java Reference
In-Depth Information
4 public class ReplaceText {
5 public static void main(String[] args) throws Exception {
6 // Check command line parameter usage
7 if (args.length != 4 ) {
8 System.out.println(
9 "Usage: java ReplaceText sourceFile targetFile oldStr newStr" );
10 System.exit( 1 );
11 }
12
13 // Check if source file exists
14 File sourceFile = new File(args[ 0 ]);
15 if (!sourceFile.exists()) {
16 System.out.println( "Source file " + args[ 0 ] + " does not exist" );
17 System.exit( 2 );
18 }
19
20 // Check if target file exists
21 File targetFile = new File(args[ 1 ]);
22 if (targetFile.exists()) {
23 System.out.println( "Target file " + args[ 1 ] + " already exists" );
24 System.exit( 3 );
25 }
26
27 try (
28 // Create input and output files
29 Scanner input = new Scanner(sourceFile);
30 PrintWriter output = new PrintWriter(targetFile);
31 ) {
32 while (input.hasNext()) {
33 String s1 = input.nextLine();
34 String s2 = s1.replaceAll(args[ 2 ], args[ 3 ]);
35 output.println(s2);
36 }
37 }
38 }
39 }
check command usage
source file exists?
target file exists?
try-with-resources
create a Scanner
create a PrintWriter
has next?
read a line
In a normal situation, the program is terminated after a file is copied. The program is
terminated 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).
12.30
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 12.13, WriteData.java?
What would happen if the close() method were not invoked in Listing 12.13?
Check
Point
12.31
Show the contents of the file temp.txt after the following program is executed.
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();
}
}
 
 
Search WWH ::




Custom Search