使用Java比较两个文件中的字符串

时间:2015-08-17 05:42:16

标签: java string-comparison

public class comparee {

static int count=0;
public static void main(String[] args) throws IOException {

    String a,b;

    FileReader fi = new FileReader(new File("C:\\Users\\IBM_ADMIN\\Desktop\\SAM_PUBLIC_MONTHLY_20150802\\a.txt"));  // new file

    FileReader fii = new FileReader(new File("C:\\Users\\IBM_ADMIN\\Desktop\\SAM_PUBLIC_MONTHLY_20150802\\b.txt"));  // new file

    BufferedReader br =new BufferedReader(fi); //new

    BufferedReader br1 =new BufferedReader(fii); //old
    FileWriter fw = new FileWriter(new File("C:\\Users\\IBM_ADMIN\\Desktop\\SAM_PUBLIC_MONTHLY_20150802\\samnew.txt"));

    int count = 0;
    while((a=br.readLine()) != null)
    {

        while((b=br1.readLine()) != null)
        {

            if(!(a.equals(b))) 
            {
                count++;
                fw.write(a);
            }

        }
        System.out.println(count);

    }


}
}

嗨,我试图通过逐行阅读来比较a.txt和b.txt中的字符串。 我想在samdata.txt上写一行,该行在a.txt中不可用,但在b.txt上可用。将不胜感激任何帮助:)谢谢

P.S上面的代码逻辑不正确

2 个答案:

答案 0 :(得分:0)

比较文件是一项复杂的操作,因为您通常需要向前看两个文件才能找到下一个匹配的行。

现在,如果你绝对(!)确定b.txt包含来自a.txt的所有行,与a.txt的顺序相同,但是在不同的地方插入了额外的行,那么下面的可能没问题。

BTW:您的变量名称令人困惑,因此我重命名它们并使用try-with-resources确保读者和作者关闭。

File fileA = new File("C:\\Users\\IBM_ADMIN\\Desktop\\SAM_PUBLIC_MONTHLY_20150802\\a.txt");
File fileB = new File("C:\\Users\\IBM_ADMIN\\Desktop\\SAM_PUBLIC_MONTHLY_20150802\\b.txt");
File fileNew = new File("C:\\Users\\IBM_ADMIN\\Desktop\\SAM_PUBLIC_MONTHLY_20150802\\samnew.txt");
int count = 0;
try (Reader readerA = new BufferedReader(new FileReader(fileA));
     Reader readerB = new BufferedReader(new FileReader(fileB));
     PrintWriter writer = new PrintWriter(new FileWriter(fileNew))) {
    // Read first line of each file
    String lineA = readerA.readLine();
    String lineB = readerB.readLine();
    // Compare lines
    while (lineA != null || lineB != null) {
        if (lineB == null) {
            // Oops! Found extra line in file A
            lineA = readerA.readLine(); // Read next line from file A
        } else if (lineA == null || ! lineA.equals(lineB)) {
            // Found new line in file B
            writer.println(lineB);
            lineB = readerB.readLine(); // Read next line from file A
            count++;
        } else {
            // Lines are equal, so read next line from both files
            lineA = readerA.readLine();
            lineB = readerB.readLine();
        }
    }
}
System.out.println(count);

答案 1 :(得分:0)

为什么不将b.txt读入列表,然后在代码中检查您在a.txt中读取的每一行是否在列表中可用(list.contains())。