逐个字符地比较两个文件

时间:2013-11-20 15:40:39

标签: java loops while-loop

这是我的代码:

public static void main(String[] args) {
    Scanner console = new Scanner(System.in); 
    System.out.print("Type first file name to use: ");
    String filename1 = console.nextLine();
    System.out.print("Type second file name to use: ");
    String filename2 = console.nextLine();
    Scanner input1 = new Scanner(new File(filename1));
    Scanner input2 = new Scanner(new File(filename2));
    String s1 = input1.next();
    String s2 = input2.next();
    boolean similar=true;r
while(!input1.hasNext()&&!input2.hasNext()){
// this is where i am stuck. i need to compare the lines character by character, but i'm not sure how to do so. i can't use buffer method, or any really advanced methods since i am just a beginner, so sticking to the basic loops (while, iff, for.. ) is the only option i have
} 

程序应该提示用户输入两个文件名并根据文件是否具有相同内容打印真或假。它应该逐个字符地检查文件并忽略差异(大写和小写)in字母是字母的情况。谢谢。

4 个答案:

答案 0 :(得分:0)

使用:

if (s1.equalsIgnoreCase(s2)) {
    // All characters on the entire line are equal.
} else {
    // There is a difference
}

它将逐个字符地逐个字符地比较字符串。

您可以创建一个循环,但这需要更多代码,并且会导致性能下降。

答案 1 :(得分:0)

字符字符,不允许当前结构做任何工作?,怎么样......

while(!input1.hasNext()&&!input2.hasNext())
{
  char c1 = input1.next(".");
  char c2 = input2.next(".");

  if (c1!=c2)
  {
    //Files are not equal
  }
}

答案 2 :(得分:0)

如果您愿意,可以使用Reader的实例处理char-by-char文件。 类似的东西:

BufferedReader reader1 = new BufferedReader(new FileReader("fileName1"));
BufferedReader reader2 = new BufferedReader(new FileReader("fileName2"));
int char1; // from first file
int char2; // from second file
// loop until the end of either file is reached
while ((char1 = reader1.read()) != -1 && (char2 = reader2.read()) != -1) {
    // convert current characters from both files to lowerCase
    char lowerCase1 = Character.toLowerCase((char) char1);
    char lowerCase2 = Character.toLowerCase((char) char2);
    if (lowerCase1 != lowerCase2) {
        System.out.println("your text files are different!");
        return;
    }
} 

答案 3 :(得分:0)

你应该这样做:

public static void main(String[] args) {
    Scanner console = new Scanner(System.in); 
    System.out.print("Type first file name to use: ");
    String filename1 = console.nextLine();
    System.out.print("Type second file name to use: ");
    String filename2 = console.nextLine();
    Scanner input1 = new Scanner(new File(filename1));
    Scanner input2 = new Scanner(new File(filename2));
    String s1 = input1.next();
    String s2 = input2.next();
    boolean similar=true;r
    while(!input1.hasNext()&&!input2.hasNext()){
        if (a.findInLine(".").compareToIgnoreCase(b.findInLine(".")) != 0) {
            similar = false;
            break;
        }
    }

    if (similar && (a.hasNext() || b.hasNext())) // unequal sizes
        similar = false;
    System.out.println("Files are " + (similar ? "equal" : "unequal"));
    return 0;
}