Compare Contents of two InputStream in Java using Apache Commons IO
Tags: Compare IOUtils Apache Commons Apache Commons IO InputStream FileInputStream
In this Java tutorial we show you how to compare the contents of two InputStream in Java using the IOUtils class of Apache Commons IO library.
How to add Apache Commons IO library to your Java project
To use the Apache Commons IO library in the Gradle build project, add the following dependency into the build.gradle file.
implementation 'commons-io:commons-io:2.8.0'
To use the Apache Commons IO library in the Maven build project, add the following dependency into the pom.xml file.
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
To have more information about the Apache Commons IO library you can visit the library home page at commons.apache.org/proper/commons-io/
How to compare the contents of two InputStream
In the following Java program, we show you how to use the IOUtils.contentEquals() of Apache Commons IO library to compare two InputStream objects.
CompareTwoInputStream.java
import org.apache.commons.io.IOUtils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class CompareTwoInputStream {
public static void main(String... args) {
try {
InputStream inputStream1 = new FileInputStream("D:\\Data\\data.txt");
InputStream inputStream2 = new FileInputStream("D:\\Data\\data.txt");
InputStream inputStream3 = new FileInputStream("D:\\Data\\data1.txt");
boolean result1 = IOUtils.contentEquals(inputStream1, inputStream2);
boolean result2 = IOUtils.contentEquals(inputStream1, inputStream3);
System.out.println("Result of compare data.txt and data.txt: " + result1);
System.out.println("Result of compare data.txt and data1.txt: " + result2);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Result of compare data.txt and data.txt: true
Result of compare data.txt and data1.txt: false
Happy Coding 😊