Share on Google+Share on Google+

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 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..


import java.util.*;

public class FileRead {
  public static void main(String[] argsthrows {

    BufferedReader bfr2 = new BufferedReader(new InputStreamReader(;
    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;



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

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


Download this code



Posted on: July 6, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null