Hello folks
I made this program to compare to text files. It reads the two files and prints out the difference between them. It works with the code i commented out, and when i know the exact name of the files. But i want some kind of interaction that keeps asking for a files that exist inside the directory. But when I try to run the code that i made for that, I get a error. It seems like i can't convert the input to a string. Can anyone tell me what i'm doing wrong?
Thanks.
import java.io.*;
import java.util.*;
public class Ch6pp2
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner tastatur = new Scanner(System.in);
//calls the getInput method
Scanner input1 = getInput(tastatur);
Scanner input2 = getInput(tastatur);
String one = input1.toString();
String two = input2.toString();
//calls the compare two files method
compareTwoFiles(one, two);
}
//this method ask for a file name until it finds a file name that exist inside the directory
public static Scanner getInput(Scanner tastatur)
{
Scanner result = null;
while (result == null)
{
System.out.print("input file name? ");
String name = tastatur.nextLine();
try
{
result = new Scanner(new File(name));
} catch (FileNotFoundException e)
{
System.out.println("File not found. "
+ "Please try again.");
}
}
System.out.println();
return result;
}
//it works with this code for input. but only if you know the exact name to type
/*
System.out.println("Enter a first file name: ");
Scanner tastatur = new Scanner(System.in);
String one = tastatur.next();
System.out.println("Enter a second file name: ");
Scanner tastatur2 = new Scanner(System.in);
String two = tastatur.next();
compareTwoFiles(one, two);
*/
//this method compares the two Strings
public static void compareTwoFiles(String one, String two) throws FileNotFoundException
{
File f = new File(one);
Scanner input = new Scanner(f);
File g = new File(two);
Scanner input2 = new Scanner(g);
int count = 1;
String text = "";
String textSecond = "";
System.out.println("Difference found:");
while (input.hasNextLine())
{
text = input.nextLine();
textSecond = input2.nextLine();
if (!text.equals(textSecond))
{
System.out.println("Line " + count + ":");
System.out.println("< " + text);
System.out.println("> " + textSecond);
System.out.println();
}
count++;
}
}
}