Java File compareTo() method with examples

January 04, 2020 No comments Java IO Examples compareTo

1. Introduction

The compareTo() method lexicographically compares two given pathnames. The method can be used to order files in Java. Note that this kind of operation depends on the system where JVM was installed. In Unix systems, the alphabetic case is significant in comparing pathnames and in Windows it is not.

2. Method signature

public int compareTo(File pathname)

Parameters:

  • pathname - abstract pathname we want to be compared to pathname specified in File instance

Returns

  • - if the argument is equal to this abstract pathname,
  • < 0 - if this abstract pathname is lexicographically less than the argument,
  • > 0 - if this abstract pathname is lexicographically greater than the argument.

3. Examples

3.1. The program that compares file /tmp/frontbackend.txt with different files and directory

package com.frontbackend.java.io.examples;

import java.io.File;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File file = new File("/tmp/frontbackend.txt");

            int ttt = file.compareTo(new File("/tmp/frontbackend.ttt"));
            System.out.println("Different extension : " + ttt);

            int theSame = file.compareTo(new File("/tmp/frontbackend.txt"));
            System.out.println("The same files : " + theSame);

            int withDirectory = file.compareTo(new File("/tmp/frontbackend"));
            System.out.println("With directory : " + withDirectory);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output will be as following:

Different extension : 4
The same files : 0
With directory : 4

4. Conclusion

In this article, we presented File.compareTo() a method that can be used to check if given abstract pathname is lexicographically equal, greater or less then abstract pathname from the argument. This method can be used to order files in a directory.

{{ message }}

{{ 'Comments are closed.' | trans }}