比较java中的两个文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21764299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:32:46  来源:igfitidea点击:

Comparing two files in java

javafilewhile-loop

提问by rick

I am trying to compare two .txt files (i.e their contents), but when I execute this code my application goes into an infinite loop. Why?

我正在尝试比较两个 .txt 文件(即它们的内容),但是当我执行此代码时,我的应用程序进入了无限循环。为什么?

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;


}

回答by Kick

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 0if different and 1if equal.

由于该方法的返回类型是整数,因此0如果不同且1相等,它将返回。

回答by Jess

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. This is the output.

我在 2 个不同的小文本文件上运行它。这是输出。

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

If you think you have an infinite loop, the issue might be elsewhere.

如果您认为自己有一个无限循环,那么问题可能出在其他地方。

回答by PNS

Assuming text file inputs, an alternative implementation to the whileloop:

假设文本文件输入,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 ifis not necessary, but it is included for clarity purposes. Otherwise, the above code could be simplified to:

第一个else if不是必需的,但为了清楚起见,它被包含在内。否则,上面的代码可以简化为:

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/finallyblock, to assure that the readers are closed.

回路应放置在一个try/finally块中,以确保阅读器是关闭的。

回答by user3818494

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);
}

回答by Bikram Dhall

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();
        }

    }