简体   繁体   English

在Java中比较两个文件

[英]Comparing two files in java

I am trying to compare two .txt files (ie their contents), but when I execute this code my application goes into an infinite loop. 我正在尝试比较两个.txt文件(即它们的内容),但是当我执行此代码时,我的应用程序进入了无限循环。 Why? 为什么?

public int compareFile(String fILE_ONE2, String fILE_TWO2)throws Exception 
{

File f1 = new File(fILE_ONE2); //OUTFILE
File f2 = new File(fILE_TWO2); //INPUT

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;
int flag=1;
while ((flag==1) &&((line1 = reader1.readLine()) != null)&&((line2 = reader2.readLine()) != null)) 
{
    if (!line1.equalsIgnoreCase(line2))  
        flag=0;
    else 
        flag=1;   
}
reader1.close();
reader2.close();
return flag;


}

I converted your code into a main program. 我将您的代码转换为一个主程序。 There is no infinite loop in this code. 此代码中没有无限循环。

I am assuming you are comparing 2 text files of a small-ish size. 我假设您正在比较2个小尺寸的文本文件。

import java.io.*;

public class Diff {
    public static void main(String[] args) throws FileNotFoundException, IOException {

        File f1 = new File(args[0]);// OUTFILE
        File f2 = new File(args[1]);// INPUT

        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;
        int flag = 1;
        while ((flag == 1) && ((line1 = reader1.readLine()) != null)
                && ((line2 = reader2.readLine()) != null)) {
            if (!line1.equalsIgnoreCase(line2))
                flag = 0;
        }
        reader1.close();
        reader2.close();
        System.out.println("Flag " + flag);
    }
}

I ran it on 2 small different text files. 我在2个不同的小文本文件上运行它。 This is the output. 这是输出。

javac Diff.java && java Diff a.txt b.txt
Flag 0

If you think you have an infinite loop, the issue might be elsewhere. 如果您认为自己存在无限循环,则问题可能出在其他地方。

The code looks good, no infinite loops. 代码看起来不错,没有无限循环。 You can remove irrespective check in the code and can update the code as below: 您可以删除代码中的无关项,并可以如下更新代码:

int flag=1;
while (((line1 = reader1.readLine()) != null)&&((line2 = reader2.readLine()) != null)) 
{
    if (!line1.equalsIgnoreCase(line2)) 
    { 
        flag=0; 
        break;
    }
}

As the return type of the method is integer than it will return 0 if different and 1 if equal. 因为该方法的返回类型是整数,所以如果不同则返回0 ,如果相等则返回1

Assuming text file inputs, an alternative implementation to the while loop: 假设输入了文本文件,则是while循环的另一种实现:

while (true) // Continue while there are equal lines
{
    line1 = reader1.readLine();
    line2 = reader2.readLine();

    if (line1 == null) // End of file 1
    {
        return (line2 == null ? 1 : 0); // Equal only if file 2 also ended
    }
    else if (line2 == null)
    {
        return 0; // File 2 ended before file 1, so not equal 
    }
    else if (!line1.equalsIgnoreCase(line2)) // Non-null and different lines
    {
        return 0;
    }

    // Non-null and equal lines, continue until the input is exhausted
}

The first else if is not necessary, but it is included for clarity purposes. else if不是必需的, else if第一个,但为了清楚起见将其包括在内。 Otherwise, the above code could be simplified to: 否则,可以将以上代码简化为:

while (true) // Continue while there are equal lines
{
    line1 = reader1.readLine();
    line2 = reader2.readLine();

    if (line1 == null) // End of file 1
    {
        return (line2 == null ? 1 : 0); // Equal only if file 2 also ended
    }

    if (!line1.equalsIgnoreCase(line2)) // Different lines, or end of file 2
    {
        return 0;
    }
}

The loop should be placed in a try/finally block, to assure that the readers are closed. 循环应放在try/finally块中,以确保关闭阅读器。

Above method by Jess will fail if file2 is same as file1 but has an extra line at the end. 如果file2与file1相同,但末尾有多余的一行,则Jess的上述方法将失败。

This should work. 这应该工作。

public boolean compareTwoFiles(String file1Path, String file2Path)
            throws IOException {

    File file1 = new File(file1Path);
    File file2 = new File(file2Path);

    BufferedReader br1 = new BufferedReader(new FileReader(file1));
    BufferedReader br2 = new BufferedReader(new FileReader(file2));

    String thisLine = null;
    String thatLine = null;

    List<String> list1 = new ArrayList<String>();
    List<String> list2 = new ArrayList<String>();

    while ((thisLine = br1.readLine()) != null) {
        list1.add(thisLine);
    }
    while ((thatLine = br2.readLine()) != null) {
        list2.add(thatLine);
    }

    br1.close();
    br2.close();

    return list1.equals(list2);
}

if you use java8, the code below to compare file contents 如果使用java8,则下面的代码比较文件内容

public boolean compareTwoFiles(String file1Path, String file2Path){
      Path p1 = Paths.get(file1Path);
      Path p1 = Paths.get(file1Path);

try{
        List<String> listF1 = Files.readAllLines(p1);
    List<String> listF2 = Files.readAllLines(p2);
    return listF1.containsAll(listF2);

        }catch(IOException ie) {
            ie.getMessage();
        }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM