Java Reference
In-Depth Information
else if (!f2.hasNextLine()) //second file ends, but not the first
System.out.printf("\n%s, with %d lines, is a subset of %s\n",
file2, numMatch, file1);
else { //mismatch found
System.out.printf("\nThe files differ at line %d\n", ++numMatch);
System.out.printf("The lines are \n%s\n and \n%s\n", line1, line2);
}
f1.close();
f2.close();
} //end main
} //end class CompareFiles
The program does the following:
•
It prompts for the names of the files to be compared; if any of the files does not exist, a
FileNotFoundException
will be thrown.
It creates two
•
Scanner
s,
f1
and
f2
, one for each file.
•
It uses
hasNextLine
to check whether a file has more lines to read; if
true
, there is at least
another line to read, and if
false
, the end of the file has been reached.
The variable
•
numMatch
counts the number of matching lines. One line from each file is read.
If they match,
1
is added to
numMatch
, and another pair of lines is read. The
while
loop exits
naturally if one (or both) of the files comes to an end; we
break
out of the loop if a mismatch
occurs.
If the first file contains this:
one and one are two
two and two are four
three and three are six
four and four are eight
five and five are ten
six and six are twelve
and the second file contains this:
one and one are two
two and two are four
three and three are six
four and four are eight
this is the fifth line
six and six are twelve
the program will print the following:
The files differ at line 5
The lines are
five and five are ten
and
this is the fifth line
Search WWH ::
Custom Search