In: Computer Science
Write a Java program that uses printf, and takes user input to find the name of the File.
Write a program that compares to files line by line, and counts the number of lines that are different. You can use file1.txt and file2.txt when testing your program, but you must ask for the file names in the input.
main
Interactively requests the names of the two files, after creating the Scanner for the keyboard.
Creates a Scanner for each of the two files.
Calls countDifferentLines with references to the two Scanners as parameters and accepts an integer return value.
Prints the result (see sample).
countDifferentLines
Accepts references to the two Scanners as parameters
Compares the two files line by line – They may have a different number of lines
Return the number of lines that are different
Sample output
Please enter name of the first file to compare: file1.txt
Please enter name of the second file to compare: file2.txt
The files differ in 4 line(s)
import java.io.File;
import java.util.Scanner;
public class FileCompare {
public static void main(String[] args) throws
Exception {
Scanner sc = new
Scanner(System.in);
//reading file names
System.out.println("Enter name of
the first file to compare: ");
String f1 = sc.next();
System.out.println("Enter name of
the second file to compare: ");
String f2 = sc.next();
int c=countDifferentLines(new
Scanner(new File(f1)), new Scanner(new File(f2)));
System.out.println("The files
differ in "+c+" line(s)");
}
private static int countDifferentLines(Scanner sc1,
Scanner sc2) throws Exception {
int count = 0;
String l1 = "", l2 = "";
//looping the files
while (sc1.hasNext() ||
sc2.hasNext()) {
//reading
lines
if(sc1.hasNext())
l1 =
sc1.nextLine();
if(sc2.hasNext())
l2 =
sc2.nextLine();
//checking the
difference
if (l1 == null
&& l2 == null)
return count;
if (l1 == null
&& l2 != null)
count++;
else if (l1 !=
null && l2 == null)
count++;
else if
(!l1.equals(l2))
count++;
}
//returns count
return count;
}
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me