Reputation: 1
This is what I have so far. I'm not sure where to go from here. I need a method to output the difference in two files
package JwolfrumCh6;
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class JwolfrumCh6 {
public static void main(String[] args) throws FileNotFoundException
{
Scanner console = new Scanner(System.in);
System.out.print("Enter File one Name");
String file1 = console.nextLine();
Scanner input1 = new Scanner(new File(file1));
System.out.print("Enter File two Name");
String file2 = console.nextLine();
Scanner input2 = new Scanner(new File(file2));
}
public static void compareFiles(Scanner input1, Scanner input2) {
while(input1.hasNextLine() || input2.hasNextLine()) {
}
}
}
Upvotes: 0
Views: 593
Reputation: 520
Call the static method in main and implement below logic in your compareFiles method.
Use removeAll method of ArrayList as shown below to get the differences in each of these files.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FML {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
System.out.print("Enter File one Name");
String file1 = console.nextLine();
Scanner input1 = new Scanner(new File(file1));
System.out.print("Enter File two Name");
String file2 = console.nextLine();
Scanner input2 = new Scanner(new File(file2));
compareFiles(input1, input2);
}
public static void compareFiles(Scanner input1, Scanner input2) {
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
while (input1.hasNextLine()) {
list1.add(input1.nextLine());
}
while (input2.hasNext()) {
list2.add(input2.nextLine());
}
List<String> tmpList = new ArrayList<String>(list1);
tmpList.removeAll(list2);
System.out.println("content from file1 which is different from file2");
for(int i=0;i<tmpList.size();i++){
System.out.println(tmpList.get(i));
}
System.out.println("content from file2 which is different from file2");
tmpList = list2;
tmpList.removeAll(list1);
for(int i=0;i<tmpList.size();i++){
System.out.println(tmpList.get(i));
}
}
}
Upvotes: 1