This post will discuss how to compare the contents of two files to check whether they are equal in Kotlin.

1. Using Files class

A simple solution is to read the entire file into a string and compare both strings for equality. The idea is to use the Files.readString() function to read all content from a file into a string, and then check the string’s equality using the contentEquals() function.

Download Code

 
Alternately, you can read all the bytes from the files into byte arrays and compare both byte arrays for equality. This can be done using the Files.readAllBytes() function, as shown below:

Download Code

2. Using BufferedReader

Reading the entire contents of a file in a String or a byte array is not preferable for large files, since it can exhaust the heap memory. For large files, consider using the BufferedReader to read the files chunk-by-chunk.

The following solution demonstrates its usage by reading the file character-by-character with the BufferedReader#read() function:

Download Code

 
Alternately, you can read a file line-by-line with BufferedReader#readLine() function:

Download Code

That’s all about comparing the contents of two files for determining equality in Kotlin.