2
import java.io.*;

public class CheckingTwoFilesAndComparing implements Serializable {

private static final long serialVersionUID = 1L;

static String FILE_ONE = "/Users/abextra/myText1.txt";
static String FILE_TWO = "/Users/abextra/myText2.txt";

public static void main(String[] args) {

    try {
        CompareFile(FILE_ONE, FILE_TWO);

    } catch (Exception e) {
        e.printStackTrace();
    }
}


private static void CompareFile(String fILE_ONE2, String fILE_TWO2)
        throws Exception {

    File f1 = new File("FILE_ONE");
    File f2 = new File("FILE_TWO");

    FileReader fR1 = new FileReader(f1);
    FileReader fR2 = new FileReader(f2);

    BufferedReader reader1 = new BufferedReader(fR1);
    BufferedReader reader2 = new BufferedReader(fR2);

    String line1 = null;
    String line2 = null;

    while (((line1 = reader1.readLine()) != null)
            &&((line2 = reader2.readLine()) != null)) {
        if (!line1.equalsIgnoreCase(line2)) {
            System.out.println("The files are DIFFERENT");
        } else {
            System.out.println("The files are identical");
        }

    }
    reader1.close();
    reader2.close();

   }
}

这是上面代码中提到的路径中存在的2个文本文件的内容

==myText1.txt===
1,This is first line, file
2,This is second line, file
3,This is third line , file
4,This is fourth line, file

==myText2.txt===
1,This is first line, file
2,This is second line, file
3,This is third  line, file
4,This is fourth line, file
5,This is fifth line, file

我是 java 的新手。我使用了 eclipse 调试器,我看到我不断收到“FileNot found”异常 - 有人可以帮忙吗?非常感谢!

4

3 回答 3

4
File f1 = new File("FILE_ONE");
File f2 = new File("FILE_TWO");

尝试在此处删除引号。您之前在程序中将 FILE_ONE 和 FILE_TWO 声明为变量,但您没有调用它们。相反,您直接调用了字符串“FILE_ONE”,当然不会找到它。因此,将其替换为您传递给 CompareFile 的参数...

File f1 = new File(fILE_ONE2);
File f2 = new File(fILE_TWO2);

并告诉我们这是否可以解决。

于 2012-10-12T01:54:06.483 回答
1

您必须从以下位置删除引号:

File f1 = new File("FILE_ONE");

File f2 = new File("FILE_TWO");

另外,请确保在文件的路径"/Users/abextra/myText1.txt"中,“用户”确实应该是大写的。在许多系统上,/users/是小写的。

于 2012-10-12T02:02:23.227 回答
1

FileNotFoundException可以在文件打开时抛出。(仅当您尝试写入已打开的文件时才会发生这种情况)

尝试关闭文件,然后运行程序。

于 2012-10-12T05:09:21.857 回答