Compare two different files line by line in Java
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.
Example 2
The following represents two files, assuming file1.txt and file2.txt, and their contents.
File1.txt
This is amazing. Java Language.
file2.txt
This is amazing. Python Language.
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(); } }
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
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); } } }
Output
Both files have same content
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.
