Write a program that compares two files and prints information about the differe
ID: 3623560 • Letter: W
Question
Write a program that compares two files and prints information about the differences between them. For example, consider a file data1.txt with the following contents:This file has a great deal of
text in it which needs to
be processed.
Consider another file data2.txt that exists with the following contents:
This file has a grate deal of
text in it which needs to
bee processed.
A dialogue with the user running your program might look like the following:
Enter a first file name: data1.txt
Enter a second file name: data2.txt
Differences found:
Line 1:
< This file has a great deal of
>This file has a grate deal of
Line 4:
< be processed.
> bee processed.
Explanation / Answer
please rate - thanks
the book doesn't say what to do if the files are different sizes, so I added that check at the end (see the red-you can just take it out)
import java.util.*;
import java.io.*;
public class RegesChapt6num2
{public static void main(String[] args)throws FileNotFoundException
{int line=0;
String buf1,buf2,filename;
Scanner in=new Scanner(System.in);
System.out.print("Enter a first file name: ");
filename=in.next();
Scanner in1=new Scanner(new File(filename));
System.out.print("Enter a second file name: ");
filename=in.next();
Scanner in2=new Scanner(new File(filename));
System.out.println("Differences found");
while(in1.hasNext()&&in2.hasNext())
{line++;
buf1=in1.nextLine();
buf2=in2.nextLine();
if(buf1.compareTo(buf2)!=0)
{System.out.println("Line "+line);
System.out.println("< "+buf1);
System.out.println("> "+buf2);
System.out.println();
}
}
if(in1.hasNext())
System.out.println("Note: file 1 has more data, file 2 does not");
else if(in2.hasNext())
System.out.println("Note: file 2 has more data, file 1 does not");
in1.close();
in2.close();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.