Java Reference
In-Depth Information
Suppose a text file named test.txt contains a line
input from file
34 567
After the following code is executed,
Scanner input = new Scanner( new File( "test.txt" ));
int intValue = input.nextInt();
String line = input.nextLine();
intValue contains 34 and line contains the characters ' ' , 5 , 6 , and 7 .
What happens if the input is entered from the keyboard ? Suppose you enter 34 , press the
Enter key, then enter 567 and press the Enter key for the following code:
input from keyboard
Scanner input = new Scanner(System.in);
int intValue = input.nextInt();
String line = input.nextLine();
You will get 34 in intValue and an empty string in line . Why? Here is the reason. The
token-reading method nextInt() reads in 34 and stops at the delimiter, which in this case is
a line separator (the Enter key). The nextLine() method ends after reading the line separa-
tor and returns the string read before the line separator. Since there are no characters before
the line separator, line is empty.
You can read data from a file or from the keyboard using the Scanner class. You can also
scan data from a string using the Scanner class. For example, the following code
scan a string
Scanner input = new Scanner( "13 14" );
int sum = input.nextInt() + input.nextInt();
System.out.println( "Sum is " + sum);
displays
The sum is 27
12.11.5 Case Study: Replacing Text
Suppose you are to write a program named ReplaceText that replaces all occurrences of a
string in a text file with a new string. The file name and strings are passed as command-line
arguments as follows:
java ReplaceText sourceFile targetFile oldString newString
For example, invoking
java ReplaceText FormatString.java t.txt StringBuilder StringBuffer
replaces all the occurrences of StringBuilder by StringBuffer in the file FormatString
.java and saves the new file in t.txt .
Listing 12.16 gives the program. The program checks the number of arguments passed to
the main method (lines 7-11), checks whether the source and target files exist (lines 14-25),
creates a Scanner for the source file (line 29), creates a PrintWriter for the target file
(lineĀ 30), and repeatedly reads a line from the source file (line 33), replaces the text (line 34),
and writes a new line to the target file (line 35).
L ISTING 12.16
ReplaceText.java
1 import java.io.*;
2 import java.util.*;
3
 
 
Search WWH ::




Custom Search