Home > Java > javaTutorial > Compare two different files line by line in Java

Compare two different files line by line in Java

WBOY
Release: 2023-08-23 15:37:08
forward
1785 people have browsed it

In this article, we will compare two different text files saved in the system. We examine each text file line by line and by comparison we can identify similarities and differences.

Let's see how to implement it using Java programming language.

Show you some examples

Example 1

The image below depicts two different text files with the same content, so the output will be two files with the same content.

Compare two different files line by line in Java

Example 2

The following represents two files, assuming file1.txt and file2.txt, and their contents.

File1.txt

This is amazing.
Java Language.
Copy after login

file2.txt

This is amazing.
Python Language.
Copy after login

Here, we can notice that the two files have different content on line 2. Since file 1, line 2 contains "Java language" and file 2, line 2 contains "Python language"

algorithm

  • Step 1 − Create reader1 and reader2 as two BufferedReader objects and use them to read two input text files line by line.

  • Step 2 - Create two variables. First, create a Boolean variable called "areEqual" and initialize it to true. Second, create an int variable called "lineNum" and initialize it to 1. areEqual is a flag variable that is initially set to true and changes to false when the contents of the input files differ. The number of lines will be saved in lineNum.

  • Step 3 - Read the contents of file 1 into line 1 and the contents of file 2 into line 2.

  • Step 4 - Read the lines in files file1 and file2 into line1 and line2 respectively until both files have been read. If line1 or line2 is empty, set "areEqual" to false.

  • Step 5 − If areEqual is true, declare the contents of the two files to be the same. If the value of areEqual is false, the contents of the declared files are different.

  • Step 6 - Close the resource.

Multiple methods

We provide solutions in different ways.

  • By using the BufferedReader class

  • By using memory mapped files

View the program and its output one by one.

Method 1: Use the BufferedReader class

Example

In this method, you will create an object of the BufferedReader class and use the built-in readLine() method to read the contents of the two files and compare them.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main{   
   public static void main(String[] args) throws IOException{   

   BufferedReader reader1 = new BufferedReader(new FileReader("E:\file1.txt"));  
   BufferedReader reader2 = new BufferedReader(new FileReader("E:\file2.txt"));
      String line1 = reader1.readLine();    
      String line2 = reader2.readLine();
      int lineNum = 1;  
      boolean areEqual = true;
      while (line1 != null || line2 != null){
         if(line1 == null || line2 == null){
            areEqual = false; 
            break;
         } else if(! line1.equalsIgnoreCase(line2)) {
            areEqual = false; 
            break;
         }
         line1 = reader1.readLine();  
         line2 = reader2.readLine();
         lineNum++;
      }
      if(areEqual){
         System.out.println("Both the files have same content");
      } else {
         System.out.println("Both the files have different content");
         System.out.println("In both files, there is a difference at line number: "+lineNum); 
         System.out.println("One file has "+line1+" and another file has "+line2+" at line "+lineNum);
      }
      reader1.close();
      reader2.close();
   }
}
Copy after login

Output

Both the files have different content
In both files, there is a difference at line number: 2
One file has Java Language. and another file has Python Language. at line 2
Copy after login

Note - The input scenario here is similar to Example 2 explained above.

Method 2: Using memory mapped files

Example

In this method, we will utilize the concept of memory mapped file, which is a kernel object that maps the bytes of the disk file to the system memory address. By manipulating the contents of the memory mapped file, we can know that the contents are the same Still different.

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;  
import java.io.RandomAccessFile; 
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class Main {  
   public static void main(String[] args) {
      Path path1 = Paths.get("E://file1.txt");
      Path path2 = Paths.get("E://file2.txt");
      compare(path1,path2);
   }
   public static void compare(Path path1, Path path2) {
      try {
         RandomAccessFile randomAccessFile1 = new RandomAccessFile(path1.toFile(), "r"); 
         RandomAccessFile randomAccessFile2 = new RandomAccessFile(path2.toFile(), "r");
         FileChannel ch1 = randomAccessFile1.getChannel();
         FileChannel ch2 = randomAccessFile2.getChannel();
         if (ch1.size() != ch2.size()) {
            System.out.println("Both files have different content");
         }
         long size = ch1.size();
         MappedByteBuffer m1 = ch1.map(FileChannel.MapMode.READ_ONLY, 0L, size);
         MappedByteBuffer m2 = ch2.map(FileChannel.MapMode.READ_ONLY, 0L, size);
         if (m1.equals(m2)) {
            System.out.println("Both files have same content");
         }
      }
      catch(Exception e){
         System.out.println(e);
      }
   }
}
Copy after login

Output

Both files have same content
Copy after login

Note - Here we are considering two files, they have the same content.

In this article, we explored how to compare the contents of two different text files line by line in Java.

The above is the detailed content of Compare two different files line by line in Java. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template