Java Reference
In-Depth Information
This is the only statement that mentions the external file name. The rest of the program is written in terms of in .
Of course, we can be even more flexible and write this:
Scanner in = new Scanner(new FileReader(fileName));
When the program is run, we supply the name of the file in fileName , with something like this:
System.out.printf("Enter file name: ");
String fileName = kb.nextLine(); //Scanner kb = new Scanner(System.in);
This example also illustrates how to read data from the keyboard (standard input) and a file in the same program.
For example, kb.nextInt() will read an integer typed at the keyboard, and in.nextInt() will read an integer from the
file input.txt .
7.4 Example: Comparing Two Files
Consider the problem of comparing two files. The comparison is done line by line until a mismatch is found or one of
the files comes to an end. Program P7.1 shows how we can solve this problem.
Program P7.1
import java.io.*;
import java.util.*;
public class CompareFiles {
public static void main(String[] args) throws IOException {
Scanner kb = new Scanner(System.in);
System.out.printf("First file? ");
String file1 = kb.nextLine();
System.out.printf("Second file? ");
String file2 = kb.nextLine();
Scanner f1 = new Scanner(new FileReader(file1));
Scanner f2 = new Scanner(new FileReader(file2));
String line1 = "", line2 = "";
int numMatch = 0;
while (f1.hasNextLine() && f2.hasNextLine()) {
line1 = f1.nextLine();
line2 = f2.nextLine();
if (!line1.equals(line2)) break;
++numMatch;
}
if (!f1.hasNextLine() && !f2.hasNextLine())
System.out.printf("\nThe files are identical\n");
else if (!f1.hasNextLine()) //first file ends, but not the second
System.out.printf("\n%s, with %d lines, is a subset of %s\n",
file1, numMatch, file2);
 
Search WWH ::




Custom Search