How to read and compare content of two different text file


 

How to read and compare content of two different text file

In this tutorial you will see how to read and compare content of two different text file.

In this tutorial you will see how to read and compare content of two different text file.

Description:

In the given example you will see how a two text file's content are compared. The BufferedReader
class allow us to read a file. The readLine() method used to read the contents of the specified file. 
The way of comparison is in such a way that it takes content of a file and assign it to as a string and
then compare it with the other file's content which too assigned as string..

Code:

import java.io.*;
import java.util.*;

public class FileRead {
  public static void main(String[] argsthrows java.io.IOException {

    BufferedReader bfr2 = new BufferedReader(new InputStreamReader(
        System.in));
    System.out.println("Enter File name:");
    String str = bfr2.readLine();
    System.out.println("Enter another file name:");
    String str1 = bfr2.readLine();

    String s1 = "";
    String s2 = "", s3 = "", s4 = "";
    String y = "", z = "";

    BufferedReader bfr = new BufferedReader(new FileReader(str));
    BufferedReader bfr1 = new BufferedReader(new FileReader(str1));

    while ((z = bfr1.readLine()) != null)
      s3 += z;

    while ((y = bfr.readLine()) != null)
      s1 += y;

    System.out.println();

    System.out.println(s3);

    if (s3.equals(s1)) {
      System.out.println("Content of both files are same");
    else {

      System.out.println("Content of both files are not same");
    }
  }
}

Output:

Download this code

Ads