Java File 1 Fred\'s Home Page This is Fred\'s Home Page Hi! My name is Fred, and
ID: 3670833 • Letter: J
Question
Java
File 1
Fred's Home Page
This is Fred's Home Page
Hi! My name is Fred, and this web site is all about me!
Here are some things I want to share:
My Hobbies
My Pets
Here is a picture I like!
---------------------
File 2
Fred's Home Page
Fred's Home Page
Hi! My name is Fred, and this web site is all about me!
Here are some things I want to share:
Here is a picture I like!
Write a program that compares two text files for equality. Print out any lines that are different along with the line number. Include the following: File I/O Exception Handling using a Try/Catch Block Algorithm: Initial and Refined Internal Documentation All prologue information The two external files Use the following two files: File.txt and File2.txt. These files are included. I have also attached zip files containing them because sometimes the files are converted to HTML files when downloaded.Explanation / Answer
import java.io.*;
import java.util.Scanner;
public class A41v2
{
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter first file's name: ");
String file1 = keyboard.next();
System.out.print("Enter second file's name: ");
String file2 = keyboard.next();
System.out.println(" ");
File inputFile1 = new File(file1);
Scanner infile1 = new Scanner(inputFile1);
File inputFile2 = new File(file2);
Scanner infile2 = new Scanner(inputFile2);
compareFiles(infile1,infile2);
}
public static void compareFiles(Scanner infile1, Scanner infile2) throws IOException
{
int counter = 1;
String line1 = readFrom(infile1);
String line2 = readFrom(infile2);
while(line1 != null && line2 != null)
{
int answer = line1.compareTo(line2);
if(answer != 0)
{
System.out.println("Difference found in line " + counter);
printLine("<",line1);
printLine(">",line2);
}
if(line1.hasNext() && line2.hasNext())
{
line1 = readFrom(infile1);
line2 = readFrom(infile2);
counter++;
}
else
break;
}
}
public static String readFrom(Scanner infile) throws IOException
{
String line = infile.nextLine();
if(line==null)
return null;
else
return line;
}
public static void printLine(String prefix, String line)
{
System.out.println(prefix + line);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.