w3resource

Java: Compare two files lexicographically


6. Compare Files Lexicographically

Write a Java program to compare two files lexicographically.

According to Wikipedia:
In mathematics, the lexicographic or lexicographical order (also known as lexical order, dictionary order, alphabetical order or lexicographic(al) product) is a generalization of the way the alphabetical order of words is based on the alphabetical order of their component letters. This generalization consists primarily in defining a total order over the sequences (often called words in computer science) of elements of a finite totally ordered set, often called alphabet.

Sample Solution:

Java Code:

import java.io.File;
public class Exercise6 {
   public static void main(String[] args) 
   {
       String str1 = "Java exercises";
       String str2 = "Java exercises";
       String str3 = "Java examples";

       int var1 = str1.compareTo( str2 );
       System.out.println("str1 & str2 comparison: "+var1);

       int var2 = str1.compareTo( str3 );
       System.out.println("str1 & str3 comparison: "+var2);

    }
}

Sample Output:

str1 & str2 comparison: 0                                                                                     
str1 & str3 comparison: 4 

Flowchart:

Flowchart: Compare two files lexicographically


For more Practice: Solve these Related Problems:

  • Write a Java program to compare two files lexicographically by reading them as streams of bytes.
  • Write a Java program to sort two files based on their content’s lexicographic order and output the comparison result.
  • Write a Java program to compare files lexicographically using a custom comparator that ignores case differences.
  • Write a Java program to compare two text files line by line lexicographically and report the first mismatch.

Go to:


PREV : Check File or Directory.
NEXT : Get File Last Modified Date.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.